文章字数:392,阅读全文大约需要1分钟
ReflectionUtils是spring针对反射提供的工具类。
handleReflectionException异常处理
源码
1 | public static void handleReflectionException(Exception ex) { |
主要是将反射中的异常分成几个部分,规范化输出
boolean declaresException(Method method, Class<?> exceptionType)
判断方法上是否声明了指定的异常类型
findField查找字段
Field findField(Class<?> clazz, String name, Class<?> type)
查找指定类的指定名称和指定类型的方法
1 | public static Field findField(Class<?> clazz, String name, Class<?> type) { |
获取所有的方法,然后循环遍历,知道找到满足条件的返回
其中getDeclaredFields(searchType)方法使用ConcurrentReferenceHashMap将Field缓存,并优先从缓存中取。
Field findField(Class<?> clazz, String name)
设置字段setField
void setField(Field field, Object target, Object value)设置指定字段的值
直接使用Field.set/get方法,然后格式化处理了异常Object getField(Field field, Object target)获取指定字段的值
查找方法findMethod
Method findMethod(Class<?> clazz, String name, Class<?>... paramTypes)
查找方法,方法的参数是一个可变长的ClassMethod findMethod(Class<?> clazz, String name)直接查,不指定参数
调用方法invokeMethod
Object invokeMethod(Method method, Object target, Object... args)调用方法Object invokeMethod(Method method, Object target)简单版本
判断类
boolean declaresException(Method method, Class<?> exceptionType)
方法上是否声明了指定的异常boolean isPublicStaticFinal(Field field)
判断字段首付是public static final的boolean isEqualsMethod(Method method)
判断方法是否是equals方法boolean isHashCodeMethod(Method method)
判断方法是否是hashcode方法boolean isToStringMethod(Method method)
判断方法是否是toString方法boolean isObjectMethod(Method method)
判断方法是否是Object类上的方法
操作
void makeAccessible(Field field)
使私有的字段可写void makeAccessible(Method method)
私有方法可调用void makeAccessible(Constructor<?> ctor)
私有构造器可调用void doWithLocalMethods(Class<?> clazz, MethodCallback mc)
遍历类上的方法,并执行回调
1 | public interface MethodCallback { |
void doWithMethods(Class<?> clazz, MethodCallback mc, MethodFilter mf)
增加了一个方法过滤器
1 | public interface MethodFilter { |