一、前言
在java中,可以通过反射获取类中的所有属性和方法,要判断类中是否包含某个方法或某个属性,使用常见的 getMethod() / getDeclaredMethod() 和 getField() / getDeclaredField() 即可获得对象方法、属性;再判断对象是否为null,即属性是否存在。
这里有一个问题,若当前类的父类的私有属性、私有方法;是获取不到的,这导致判断并不是很准确,有什么更好的办法呢?
二、是否存在某个方法
1、常规判断方法如下 --- 不够完善 :
public boolean hasMethod(Class clzz, String methodName, Class[] argsType) {
// 从当前类查找
try {
Method declaredMethod = clzz.getDeclaredMethod(methodName, argsType);
if (declaredMethod != null) {
return true;
}
} catch (NoSuchMethodException e) {
}
// 从父类中查找
try {
Method method = clzz.getMethod(methodName, argsType);
if (null != method) {
return true;
}
} catch (NoSuchMethodException e) {
}
return false;
}
2、新的方法 --- 判断父类的私有方法
public boolean hasMethod2(Class clzz, String methodName, Class[] argsType) {
Method method = ReflectionUtils.findMethod(clzz, methodName, argsType);
if(null != method){
return true;
}
return false;
}
三、是否存在某个字段
1、判断是否存在某个字段 --- 不够完善:
public boolean hasField(Class clzz, String fieldName) {
// 从当前类中查找
Field declaredField = null;
try {
declaredField = clzz.getDeclaredField(fieldName);
} catch (NoSuchFieldException e) {
}
if (null != declaredField) {
return true;
}
// 从父类中查找 -- 仅限public方法
Field field = null;
try {
field = clzz.getField(fieldName);
} catch (NoSuchFieldException e) {
}
if (null != field) {
return true;
}
return false;
}
2、新的方法 --- 判断父类的私有属性
public boolean hasField2(Class clzz, String fieldName) {
Field field = ReflectionUtils.findField(clzz, fieldName);
if (field != null) {
return true;
}
return false;
}
四、总结
1、ReflectionUtils 工具类:位于 spring-core 包,完整包名是:org.springframework.util.ReflectionUtils 。
2、ReflectionUtils.findField() 方法能获取到父类的私有属性,原理也是很简单的:
- 获取当前类的所有属性,判断有没有获取到
- 获取上一级父类的Class对象 ,继续获取所有属性判断
- 当上级父类 不等于 Object.class 时,重复执行上一个步骤
参考资料: getFields和 getDeclaredFields 方法的区别
getMethods 和 getDeclaredMethods 方法的区别



