在反射方法的时候,如果某方法没有参数
好像有下面两种方法去获得
getMethod(method_name_str, new Class[]{});
或者
getMethod(method_name_str, null);
请问这两种方法有区别吗?
高洛峰2017-04-18 10:50:53
In terms of effect, after Class
类的 getMethod
方法,这两种参数没有区别。
我们可以查看 getMethod
的源码,getMethod
is called layer by layer, the following method will be used:
In this method, you can see that there is a arrayContentsEq
method used to match the parameters of the method:
It can be found that for the case where parameterTypes is null
, and for the case where null
的情况,和对于 parameterTypes 为空数组(length == 0)的情况,效果是一样的 —— 假设此时我们要获取的方法 m 的参数为空,那么该方法的 m.getParameterTypes()
返回的数组(a2)的长度即为 0,我们可以发现 a1 == null
或者 a1.length == 0
的时候,arrayContentsEq
方法返回的都是 true
parameterTypes
m.getParameterTypes()
of this method is 0. We can find that a1 == null
or When a1.length == 0
, the 🎜 method returns true
(that is, the match is successful). 🎜大家讲道理2017-04-18 10:50:53
If a method has no parameters, there is actually no difference between the two situations.
TrackgetMethod(String name, Class<?>... parameterTypes)
的源码,可以发现如下代码,其中a1为传入的parameterTypes
,a2
为根据参数name
找到的Method
实例调用的method.getParameterTypes()
。程序根据比较a1
和a2
来返回正确的Method
.
private static boolean arrayContentsEq(Object[] a1, Object[] a2) {
if (a1 == null) {
return a2 == null || a2.length == 0;
}
if (a2 == null) {
return a1.length == 0;
}
if (a1.length != a2.length) {
return false;
}
for (int i = 0; i < a1.length; i++) {
if (a1[i] != a2[i]) {
return false;
}
}
return true;
}