java reflectionutils_Spring中的各种Utils(五):ReflectionUtils详解(转载)

原文出处:https://blog.csdn.net/wolfcode_cn/article/details/80660515

原创文章,转载请注明出处。

本节中,我们来看看Spring针对反射提供的工具类:ReflectionUtils。反射在容器中使用是非常频繁的了,ReflectionUtils中也提供了想当多的有用的方法,一起来看看。

在ReflectionUtils中提供了一些专门用于处理在反射中异常相关的方法,这些方法一般在Spring框架内部使用,当然,出于规范考虑,我们在开发中涉及到反射的异常,也可以使用这些方法。我们按照这些方法的调用链来看代码:

void handleReflectionException(Exception ex)

处理反射中的异常,我们直接看代码:

public static void handleReflectionException(Exception ex) {

if (ex instanceof NoSuchMethodException) {

throw new IllegalStateException("Method not found: " + ex.getMessage());

}

if (ex instanceof IllegalAccessException) {

throw new IllegalStateException("Could not access method: " + ex.getMessage());

}

if (ex instanceof InvocationTargetException) {

handleInvocationTargetException((InvocationTargetException) ex);

}

if (ex instanceof RuntimeException) {

throw (RuntimeException) ex;

}

throw new UndeclaredThrowableException(ex);

}

可以看到,代码把NoSuchMethodException,IllegalAccessException,InvocationTargetException等反射中的检查异常(Exception)直接包装为对应的运行时异常(RuntimeException);这里我们可以先看一下反射中的异常:

999711b4131a639859161fe922e4d5e2.png

可以看到,反射中的异常,都继承了ReflectiveOperationException(反射操作异常),而该异常继承了Exception;旗下再是ClassNotFoundException等具体的反射操作异常;

在方法中,如果遇到的是InvocationTargetException异常,交给handleInvocationTargetException方法处理:

public static void rethrowRuntimeException(Throwable ex) {

if (ex instanceof RuntimeException) {

throw (RuntimeException) ex;

}

if (ex instanceof Error) {

throw (Error) ex;

}

throw new UndeclaredThrowableException(ex);

}

可以看到,该方法只是判断了运行时异常和Error;并原样抛出;怎么理解这个方法的调用?原因很简单,InvocationTargetException是在method.invoke的时候抛出的,方法在执行的过程中,方法本身的执行可能抛出RuntimeException或者Error,其余方法本身抛出的Exception异常直接包装为UndeclaredThrowableException(RuntimeException)处理;

统一下来,可以这样理解,除了在反射执行过程中遇到的Error,其余所有的Exception,都被统一转成了RuntimeException;

接下来进入正常方法

Field findField(Class> clazz, String name, Class> type)

根据类型,字段名称和字段类型查询一个字段;该方法会遍历的向父类查询字段,查询到的是所有字段;我们可以简单看一下实现:

public static Field findField(Class> clazz, String name, Class> type) {

Class> searchType = clazz;

while (Object.class != searchType && searchType != null) {

Field[] fields = getDeclaredFields(searchType);

for (Field field : fields) {

if ((name == null || name.equals(field.getName())) &&

(type == null || type.equals(field.getType()))) {

return field;

}

}

searchType = searchType.getSuperclass();

}

return null;

}

代码实现比较简单,向上查询字段,直到Object类型;注意,其中调用了一句代码:

Field[] fields = getDeclaredFields(searchType);

我们来看看该代码实现:

private static Field[] getDeclaredFields(Class> clazz) {

Field[] result = declaredFieldsCache.get(clazz);

if (result == null) {

result = clazz.getDeclaredFields();

declaredFieldsCache.put(clazz, (result.length == 0 ? NO_FIELDS : result));

}

return result;

}

可以看到,实际上,在该工具类中,对类型和字段做了缓存,保存到了declaredFieldsCache中,来看看这个cache的声明:

private static final Map, Field[]> declaredFieldsCache =

new ConcurrentReferenceHashMap, Field[]>(256);

因为是工具类,被声明为ConcurrentReferenceHashMap也是能够理解;

这种缓存机制也存在于方法的查询;

该方法还有一个简单的版本:

Field findField(Class> clazz, String name)

void setField(Field field, Object target, Object value)

在指定对象(target)中给指定字段(field)设置指定值(value);

Object getField(Field field, Object target)

在指定对象(target)上得到指定字段(field)的值;

以上两个方法的实现都非常简单,分别调用了field.set和field.get方法;并处理了对应的异常;选一个实现看看:

public static void setField(Field field, Object target, Object value) {

try {

field.set(target, value);

}

catch (IllegalAccessException ex) {

handleReflectionException(ex);

throw new IllegalStateException(

"Unexpected reflection exception - " + ex.getClass().getName() + ": " + ex.getMessage());

}

}

使用了handleReflectionException方法来统一处理异常;

Method findMethod(Class> clazz, String name, Class>… paramTypes)

在类型clazz上,查询name方法,参数类型列表为paramTypes;

public static Method findMethod(Class> clazz, String name, Class>... paramTypes) {

Class> searchType = clazz;

while (searchType != null) {

Method[] methods = (searchType.isInterface() ? searchType.getMethods() : getDeclaredMethods(searchType));

for (Method method : methods) {

if (name.equals(method.getName()) &&

(paramTypes == null || Arrays.equals(paramTypes, method.getParameterTypes()))) {

return method;

}

}

searchType = searchType.getSuperclass();

}

return null;

}

可以看到,该仍然可以向上递归查询方法,并且查询到的是所有方法。

该方法也有一个简单的版本:

Method findMethod(Class> clazz, String name)

Object invokeMethod(Method method, Object target, Object… args)

在指定对象(target)上,使用指定参数(args),执行方法(method);

该方法的实现也非常简单:

public static Object invokeMethod(Method method, Object target, Object... args) {

try {

return method.invoke(target, args);

}

catch (Exception ex) {

handleReflectionException(ex);

}

throw new IllegalStateException("Should never get here");

}

可以看到,就只是调用了method.invoke方法,并统一处理了调用异常;

该方法也有一个简单版本:

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方法;

可能有童鞋记得,在AopUtils中也有这几个isXXX方法,是的,其实AopUtils中的isXXX方法就是调用的ReflectionUtils的这几个方法的;

boolean isObjectMethod(Method method)

判断方法是否是Object类上的方法;

void makeAccessible(Field field)

将一个字段设置为可读写,主要针对private字段;

void makeAccessible(Method method)

将一个方法设置为可调用,主要针对private方法;

void makeAccessible(Constructor> ctor)

将一个构造器设置为可调用,主要针对private构造器;

void doWithLocalMethods(Class> clazz, MethodCallback mc)

针对指定类型上的所有方法,依次调用MethodCallback回调;

首先来看看MethodCallback接口声明:

public interface MethodCallback {

/**

* 使用指定方法完成一些操作.

*/

void doWith(Method method) throws IllegalArgumentException, IllegalAccessException;

}

其实就是一个正常的回调接口;来看看doWithLocalMethods实现:

public static void doWithLocalMethods(Class> clazz, MethodCallback mc) {

Method[] methods = getDeclaredMethods(clazz);

for (Method method : methods) {

try {

mc.doWith(method);

}catch (IllegalAccessException ex) {

throw new IllegalStateException("...");

}

}

}

其实实现很简单,就是得到类上的所有方法,然后执行回调接口;这个方法在Spring针对bean的方法上的标签处理时大量使用,比如@Init,@Resource,@Autowire等标签的预处理;

该方法有一个增强版:

void doWithMethods(Class> clazz, MethodCallback mc, MethodFilter mf)

该版本提供了一个方法匹配(过滤器)MethodFilter;

我们来看看MethodFilter的接口声明:

public interface MethodFilter {

/**

* 检查一个指定的方法是否匹配规则

*/

boolean matches(Method method);

}

该接口就声明了一个匹配方法,用于匹配规则;

再返回来看看doWithMethods方法的实现:

public static void doWithMethods(Class> clazz, MethodCallback mc, MethodFilter mf) {

// Keep backing up the inheritance hierarchy.

Method[] methods = getDeclaredMethods(clazz);

for (Method method : methods) {

if (mf != null && !mf.matches(method)) {

continue;

}

try {

mc.doWith(method);

}catch (IllegalAccessException ex) {

throw new IllegalStateException("...");

}

}

if (clazz.getSuperclass() != null) {

doWithMethods(clazz.getSuperclass(), mc, mf);

}else if (clazz.isInterface()) {

for (Class> superIfc : clazz.getInterfaces()) {

doWithMethods(superIfc, mc, mf);

}

}

}

该方法实现就很明确了,首先得到类上所有方法,针对每一个方法,调用MethodFilter实现匹配检查,如果匹配上,调用MethodCallback回调方法。该方法会递归向上查询所有父类和实现的接口上的所有方法并处理;

void doWithLocalFields(Class> clazz, FieldCallback fc)

那很明显,该方法就是针对所有的字段,执行的对应的回调了,这里的FieldCallback就类似于前面的MethodCallback:

public interface FieldCallback {

/**

* 给指定的字段执行操作;

*/

void doWith(Field field) throws IllegalArgumentException, IllegalAccessException;

}

该方法的实现就类似于doWithLocalMethods的实现了:

public static void doWithLocalFields(Class> clazz, FieldCallback fc) {

for (Field field : getDeclaredFields(clazz)) {

try {

fc.doWith(field);

}catch (IllegalAccessException ex) {

throw new IllegalStateException("...");

}

}

}

得到类上所有的字段,并执行回调;同理,该方法在Spring中主要用于预处理字段上的@Autowire或者@Resource标签;

void doWithFields(Class> clazz, FieldCallback fc, FieldFilter ff)

和doWithMethods的加强版相同,针对字段,也提供了一个拥有字段匹配(过滤)的功能方法;我们就只简单看下FieldFilter实现即可:

public interface FieldFilter {

/**

* 检查给定字段是否匹配;

*/

boolean matches(Field field);

}

小结

总的来说,ReflectionUtils提供的功能还算完整,其实想要实现这样的一个工具类,也不是什么难事,更多的建议大家多看看Spring的实现,还是有不少收获。当然,这里我们看的是Spring4.X的代码,相信在Spring5中完全使用Java8的代码,会更优雅。


版权声明:本文为weixin_39914975原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。