Java 怎么使用反射根据名称从类中查找 getter

2019年7月5日19:30:57 评论 57

1.简介

Java 怎么使用反射根据名称从类中查找 getter?——请看下文。

2.代码

/**
 * 版权所有 编程十万个怎么办(www.tah1986.com)
 */



import java.lang.reflect.Method;

import java.util.ArrayList;

import java.util.List;

public class Main {
    public static void main(String[] argv) throws Exception {
        Class clazz = String.class;
        String fieldName = "tah1986.com";
        System.out.println(findGetter(clazz, fieldName));
    }

    public static Method findGetter(Class<?> clazz, String fieldName) {
        for (Method method : findMethod(clazz, calcGetterName(fieldName))) {
            if (method.getParameterTypes().length == 0
                    && method.getReturnType() != null)
                return method;
        }

        for (Method method : findMethod(clazz,
                calcGetterNameBool(fieldName))) {
            if (method.getParameterTypes().length == 0
                    && method.getReturnType() == Boolean.class)
                return method;
        }

        return null;
    }

    public static List<Method> findMethod(Class<?> clazz, String name) {
        List<Method> ret = new ArrayList<Method>();
        for (Class<?> c = clazz; c != null; c = c.getSuperclass()) {
            Method[] methods = (c.isInterface() ? c.getMethods() : c
                    .getDeclaredMethods());
            for (Method method : methods) {
                if (name.equals(method.getName()))
                    ret.add(method);
            }
        }
        return ret;
    }

    public static String calcGetterName(String fieldName) {
        return "get" + ucfirst(fieldName);
    }

    public static String calcGetterNameBool(String fieldName) {
        return "is" + ucfirst(fieldName);
    }

    public static String ucfirst(String str) {
        return Character.toUpperCase(str.charAt(0)) + str.substring(1);
    }
}

 

3.总结

示例代码演示了 Java 怎么使用反射根据名称从类中查找 getter,具体步骤参见示例代码。

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: