提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
使用反射通过名称从类中找到Getter
//package com.nowjava; /** 来 自 时 代 J a v a - nowjava.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 = "nowjava.com"; System.out.println(findGetter(clazz, fieldName)); } /** * 时 代 J a v a - N o w J a v a . c o m 提 供 **/ 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" +