【问题标题】:How to get class from the method implemented in abstract class如何从抽象类中实现的方法中获取类
【发布时间】:2019-07-30 14:25:21
【问题描述】:

假设我有一个抽象类如下:

public abstract class Abstract{
   public void mymethod() {

   }
}

还有一个实现它的类:

public class Implementation extends Abstract {

}

我正在从实现类调用 mymethod 并检查它:

method.getDeclaringClass()
            .getDeclaredConstructor().newInstance();

这失败了,因为 Declaring 类是抽象的,所以它不能被实例化。我正在尝试弄清楚如何取而代之的是检索调用类。

【问题讨论】:

  • 你不需要实例化对象来检查类。首先你是如何获得Method 对象的?

标签: java reflection abstract-class instantiation


【解决方案1】:

不要使用声明类,使用实际类:

this.getClass()

【讨论】:

    【解决方案2】:

    它工作正常。

    Class<Implementation> im = Implementation.class;
    Method[] m = im.getMethods();
    Object o = m[0].getDeclaringClass().getDeclaredConstructor().newInstance();
    System.out.println(o.getClass());
    

    打印----

    class com.<package>.Implementation
    

    您可以循环打印方法,我刚刚粘贴了第一种方法 m[0]

    【讨论】:

    • 如果方法只在超类中怎么办,我的情况是这样?
    猜你喜欢
    • 2013-08-25
    • 2013-05-30
    • 2011-12-01
    • 1970-01-01
    • 2016-12-28
    • 2014-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多