我有以下代码:
String methodName = "main";
Method[] methods = classHandle.getMethods();
for (Method m : methods)
{
System.out.println(m.getName().equals(methodName);
}
Method classMethod = null;
try
{
classMethod = classHandle.getMethod(methodName);
}
catch(Exception e)
{
}
System.out.println(classMethod == null);
第一个 print 打印 true
,但第二个也打印 true
。
为什么会这样?
最佳答案
要获取 static void main(String [] args) 使用以下内容
classHandle.getDeclaredMethod("main", String[].class);
可能的原因(在我们知道我们在 static void main 之后写的)
- Class.getMethod(name, parameters) 仅返回公共(public)方法,也许您想对 protected 、默认的或私有(private)的方法使用 getDeclaredMethod(name, parameters)
- 参数不匹配。 “main”有任何参数吗?传递给 getDeclaredMethod() 或 getMethod() 的参数必须完全匹配。
请考虑以下事项。
private class Horse {
protected void makeNoise(int level) {
}
}
// OK
System.out.println(Horse.class.getDeclaredMethod("makeNoise", new Class<?>[]{int.class}));
// throws NoSuchMethodException - parameters don't match
System.out.println(Horse.class.getDeclaredMethod("makeNoise"));
// throws NoSuchMethodException, not a public method
System.out.println(Horse.class.getMethod("makeNoise", new Class<?>[]{int.class}));
关于java - 为什么 getmethod 返回 null 即使该方法存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28997478/