【问题标题】:Why getmethod returns null even though the method exists为什么即使方法存在getmethod返回null
【发布时间】:2015-03-11 21:14:18
【问题描述】:

我有以下代码:

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);

第一个打印输出true,但第二个打印也打印true

为什么会这样?

【问题讨论】:

  • 在方法不存在时调用classHandle.getMethod(假设classHandleClass)应该导致抛出NoSuchMethodException,而不是返回null

标签: java class reflection methods


【解决方案1】:

我假设“classHandle”是类的一种?

您的第一个循环只检查方法名称,不关心方法参数。

“public Method getMethod(String name, Class... parameterTypes)”的完整签名告诉我们,您实际上是在尝试查找名称为“methodName”的 0 参数方法。

您确定存在具有这样名称和 0 个参数的方法吗?

【讨论】:

  • 不是,其实我是在找一个类的main函数,得到String[] args。
  • 就像'public static void main(String[] args)'?那么你在'getMethod('main',...)'调用中缺少参数类型规范。
  • 在这种情况下你需要做classHandle.getMethod(methodName, String[].class);
  • @R4J 是的,但是在 JavaDoc 上写到,当不指定参数时,它就像一个空数组。
  • @JohnDoe 请告诉我们您的“主要”方法是如何声明的。
【解决方案2】:

因为方法的参数不匹配。您需要在调用 getMethod() 时指定参数类型。

【讨论】:

    【解决方案3】:

    getMethods method 返回一个包含所有Methods 的数组,而您只是检查名称。对于main,它将返回true,但对于从Object 继承的所有方法,它将返回false

    当您仅使用方法名称作为参数调用getMethod method 时,您要求的是不带参数的Method

    但是main 接受一个参数,一个String[],所以getMethod 抛出一个NoSuchMethodException。你抓住了它,但什么也不做。 (您正在“吞下”异常,这通常是个坏主意。)所以,classMethod 仍然是 nulltrue 被输出。

    要查找main,请将参数的类型作为附加参数传递:

    Method classMethod = classHandle.getMethod(methodName, String[].class);
    

    【讨论】:

      【解决方案4】:

      要获取静态 void main(String [] args),请使用以下内容

      classHandle.getDeclaredMethod("main", String[].class);
      

      可能的原因(在我们知道我们是在静态 void main 之后写的)

      • Class.getMethod(name, parameters) 只返回公共方法,也许您想将 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}));
      

      【讨论】:

        猜你喜欢
        • 2015-06-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-06-13
        • 2015-10-10
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多