【问题标题】:getMethod avoiding parent classesgetMethod 避免父类
【发布时间】:2013-05-20 20:42:14
【问题描述】:

在使用 getMethod() 时,我遇到了一个问题。我调用 getMethod() 的类有很多父方法。但是,我不想让 getMethod 注意到父类的方法,只关注我正在查看的特定类。比如……

class superClass {
    boolean equals(Object obj) {
        ....
    }
}

...

import superClass

class subClass {
    ...
}

现在如果我像这样使用 getMethod...

try{
   Class[] args = new Class[1];
   args[0] = Object.class;
   Method equalsMethod = subClass.getMethod("equals", args);
}

catch(NoSuchMethodException ex){
...
}

我不希望它从当前正在执行的超类中引入 equals 方法。我只想知道我调用 getMethod 的类(在本例中为子类)是否包含方法 equals()。

有什么办法吗?任何帮助将不胜感激。

【问题讨论】:

    标签: java reflection


    【解决方案1】:

    试试 getDeclaredMethod(String, args)。它只会返回你的类显式声明的方法,因此不涉及超级。

    【讨论】:

    • Stackoverflow... 不断向我展示我在文档中遗漏的愚蠢的小东西。哈哈。谢谢,这工作得很好。
    【解决方案2】:

    请改用subClass.getDeclaredMethod()。这样,您将获得在您的类中明确声明的方法或MethodNotFoundException

    【讨论】:

      猜你喜欢
      • 2017-10-09
      • 2023-04-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多