Java Reflection中Getters and Setters简介说明
下文讲述java反射获取获取类中所有getters和setters的方法分享,如下所示:
实现思路:
方式1:
遍历所有方法,获取get及set开头的方法
方式2:
根据一定的规则拼接get及set方法
getters和setters特点: Getter Getter方法常使用get开头,没有方法参数,返回一个值 Setter Setter方法的名字以set开头,有一个方法参数
例:
Method[] methods = clazz.getMethods();
for(Method method : methods){
if(isGetter(method)) System.out.println("getter: " + method);
if(isSetter(method)) System.out.println("setter: " + method);
}
}
public static boolean isGetter(Method method){
if(!method.getName().startsWith("get")) return false;
if(method.getParameterTypes().length != 0) return false;
if(void.class.equals(method.getReturnType()) return false;
return true;
}
public static boolean isSetter(Method method){
if(!method.getName().startsWith("set")) return false;
if(method.getParameterTypes().length != 1) return false;
return true;
}
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


