昨天在研究getDeclaredMethod(String name,Class<?>... parameterTypes)API时,发现这么一段话:
The name
parameter is a String
that specifies the simple name of the desired method, and the parameterTypes
parameter is an array of Class
objects that identify the method's formal parameter types, in declared order. If more than one method with the same parameter types is declared in a class, and one of these methods has a return type that is more specific than any of the others, that method is returned; otherwise one of the methods is chosen arbitrarily. If the name is "<init>"or "<clinit>" a NoSuchMethodException
is raised.
就此产生了疑问,如果指定了方法的名字和参数的类型,为什么还可能会得到多个方法,java中不是不允许同名同参的overloaded吗?接着在getMethod()的API中找到了答案:
Note that there may be more than one matching method in a class because while the Java language forbids a class to declare multiple methods with the same signature but different return types, the Java virtual machine does not.