cc和cc4中transform方法的区别
Nbc Lv3

commons-collections与commons-collections4中transform方法的区别

前言

这个问题是在分析CC链的时候发现的,调试的过程中突然发现transform方法看起来怎么不一样了。当时就看了一些,又是在一个阳光明媚的下午我还是打算写下来记录一下省着忘

分析

先看一下两个的源码

commons-collections

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public Object transform(Object input) {
if (input == null) {
return null;
}
try {
Class cls = input.getClass();
Method method = cls.getMethod(iMethodName, iParamTypes);
return method.invoke(input, iArgs);

} catch (NoSuchMethodException ex) {
throw new FunctorException("InvokerTransformer: The method '" + iMethodName + "' on '" + input.getClass() + "' does not exist");
} catch (IllegalAccessException ex) {
throw new FunctorException("InvokerTransformer: The method '" + iMethodName + "' on '" + input.getClass() + "' cannot be accessed");
} catch (InvocationTargetException ex) {
throw new FunctorException("InvokerTransformer: The method '" + iMethodName + "' on '" + input.getClass() + "' threw an exception", ex);
}
}

commons-collections4

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public O transform(final Object input) {
if (input == null) {
return null;
}
try {
final Class<?> cls = input.getClass();
final Method method = cls.getMethod(iMethodName, iParamTypes);
return (O) method.invoke(input, iArgs);
} catch (final NoSuchMethodException ex) {
throw new FunctorException("InvokerTransformer: The method '" + iMethodName + "' on '" +
input.getClass() + "' does not exist");
} catch (final IllegalAccessException ex) {
throw new FunctorException("InvokerTransformer: The method '" + iMethodName + "' on '" +
input.getClass() + "' cannot be accessed");
} catch (final InvocationTargetException ex) {
throw new FunctorException("InvokerTransformer: The method '" + iMethodName + "' on '" +
input.getClass() + "' threw an exception", ex);
}
}

首先处理异常的地方没有区别

主要区别在这两方面

final 关键字用于方法参数(input)和局部变量(clsmethod

使用了泛型类型 O,并且在调用 method.invoke 时进行了 (O) 类型转换

自我感觉主要就是使用泛型使得代码在类型上更加安全和灵活(就是感觉一下)

由 Hexo 驱动 & 主题 Keep
访客数 访问量