Is there any difference between:
Method getIDMethod = MyInterface.class.getMethod("getId");
and
Method getIDMethod = MyInterface.class.getMethod("getId", new Class<?>[]{});
MyInterface is as follows:
public interface MyInterface {
AnotherInterface getId();
}
No, there is no difference. An empty Class[]
will be generated implicitly in the first case.
The Java Language Specification states
Invocations of a variable arity method may contain more actual argument expressions than formal parameters. All the actual argument expressions that do not correspond to the formal parameters preceding the variable arity parameter will be evaluated and the results stored into an array that will be passed to the method invocation (§15.12.4.2).
and about the invocation and evaluating arguments
If
m
is being invoked withk ≠ n
actual argument expressions, or, ifm
is being invoked withk = n
actual argument expressions and the type of the k'th argument expression is not assignment compatible withT[]
, then the argument list(e1, ..., en-1, en, ..., ek)
is evaluated as if it were written as(e1, ..., en-1, new |T[]| { en, ..., ek })
, where|T[]|
denotes the erasure (§4.6) ofT[]
.
Technically, it would be equivalent to
new Class[]{} // instead of new Class<?>[]{}
No, there is no difference between these two, empty array means method has no parameter
but if your method accept any parameter you must use second form like
Method getIDMethod = MyInterface.class.getMethod("setId", new Class<?>[]{String.class});
public interface MyInterface {
public void setId(String arg);
}
here is declaration of getMethod
method in Class
, as you see second parameter is params array and there is no difference between sending empty array or doesn't send anything
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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.