两者之间有什么区别吗:
Method getIDMethod = MyInterface.class.getMethod("getId");
和
Method getIDMethod = MyInterface.class.getMethod("getId", new Class<?>[]{});
我的界面如下:
public interface MyInterface {
AnotherInterface getId();
}
不,没有区别。在第一种情况下,将隐式生成空Class[]
。
Java 语言规范声明
变量 arity 方法的调用可能包含更多实际 参数表达式比形式参数。所有实际参数 与前面的形式参数不对应的表达式 将评估变量 Arity 参数并存储结果 放入将传递给方法调用的数组中 (§15.12.4.2)。
以及关于调用和评估参数
如果使用
k ≠ n
实际参数表达式调用m
,或者m
正在使用k = n
实际参数表达式和类型进行调用 的第 k 个参数表达式与赋值不兼容T[]
, 然后计算参数列表(e1, ..., en-1, en, ..., ek)
,就好像 它被写成(e1, ..., en-1, new |T[]| { en, ..., ek })
,其中|T[]|
表示删除 (§4.6)T[]
。
从技术上讲,它相当于
new Class[]{} // instead of new Class<?>[]{}
不,这两者之间没有区别,空数组表示方法没有参数
但是如果你的方法接受任何参数,你必须使用第二种形式,如
Method getIDMethod = MyInterface.class.getMethod("setId", new Class<?>[]{String.class});
public interface MyInterface {
public void setId(String arg);
}
这是Class
中getMethod
方法的声明,如您所见,第二个参数是params数组,发送空数组或不发送任何东西之间没有区别
public Method getMethod(String name, Class<?>... parameterTypes)
throws NoSuchMethodException, SecurityException {
// be very careful not to change the stack depth of this
// checkMemberAccess call for security reasons
// see java.lang.SecurityManager.checkMemberAccess
checkMemberAccess(Member.PUBLIC, ClassLoader.getCallerClassLoader());
Method method = getMethod0(name, parameterTypes);
if (method == null) {
throw new NoSuchMethodException(getName() + "." + name + argumentTypesToString(parameterTypes));
}
return method;
}