集册 Java实例教程 获取字段的获取方法

获取字段的获取方法

欢马劈雪     最近更新时间:2020-01-02 10:19:05

478
获取字段的获取方法

/**
 * 时代Java - N o w  J a v a . c o m 提 供 
**/

import java.lang.reflect.Field;

import java.lang.reflect.InvocationTargetException;

import java.lang.reflect.Method;

import java.util.Collection;

import java.util.Iterator;

import java.util.LinkedList;

import java.util.List;

import java.util.logging.Level;

import java.util.logging.Logger;


public class Main{

    private static Logger log = Logger.getLogger(BeanUtil.class

            .getSimpleName());

    public static Method getGetterMethodForField(Object obj, Field field)

            throws NoSuchMethodException {

        try {

            return obj.getClass().getDeclaredMethod(

                    getGetterMethodNameForField(obj, field));

        } catch (NoSuchMethodException nsme) {

            log.log(Level.WARNING, "Can't find method.", nsme);/** 时 代 J a v a 公 众 号 提 供 **/

            throw nsme;

        }

    }

    public static Method getGetterMethodForField(Object obj,

            String fieldName) throws NoSuchMethodException,

            NoSuchFieldException {

        return obj.getClass().getDeclaredMethod(

                getGetterMethodNameForField(fieldName, obj.getClass()

                        .getDeclaredField(fieldName)));

    }

    public static Method getGetterMethodForField(Class obj, String fieldName)

            throws NoSuchMethodException, NoSuchFieldException {

        return obj.getDeclaredMethod(getGetterMethodNameForField(fieldName,

                obj.getDeclaredField(fieldName)));

    }

    public static String getGetterMethodNameForField(Object obj, Field field) {

        if (field.getType() == Boolean.class

                || field.getType() == boolean.class) {

            String isGetterName = "is"

                    + field.getName().substring(0, 1).
展开阅读全文