开发者

Can a method in an abstract class use reflection to get information about the instantiating class?

I was wondering if a metho开发者_运维百科d within an abstract class could get information about the instantiating class, for example, the number of constructor methods and the types of arguments they take.

Further, I was wondering if it'd be possible to know which one of the above was called for the particular instantiation.

Thanks


I think you can.

package test;

public abstract class AbstractClass {

    public abstract String something();

    public void printConstructorsOfInstantiatingClass() {
        System.out.println(getClass().getDeclaredConstructors());
    }
}

package test;

public class ConcreteClass extends AbstractClass {
    @Override
    public String something() {
        return "concreteSomething";
    }
}

package test;

public class TestMain {
    public static void main(String[] args) {
        ConcreteClass cc = new ConcreteClass();
        cc.printConstructorsOfInstantiatingClass();
    }
}

same works with getDeclaredMethods and other methods concerning reflection.


I haven't tested this, but I believe that if you implement the reflection code in the abstract class, in runtime you'll get the info of the actual Class that extends your abstract (if you use something like this.getClass()... etc).

As to which constructor was called, I don't believe it's possible using reflection only, since after the object was created, there is no record of what method was called before.


As already answered, getClass() will return the concrete class and is what you are looking for.

As to which constructor is being called, your best bet is to throw an exception, catch it, and then walk up the stack frames until you find the constructor call you are looking for. Not too clean, but I think this is the best you can do.


I believe you can use getClass().getEnclosingClass() to get the parent class if the current class is anonymous or nested. If that doesn't work, try getClass().getDeclaringClass().

Use getConstructors() to find the constructors of the declaring class. I don't think there is any way to determine which constructor was invoked to instantiate the declaring class... unless your code is run during the constructor of the declaring class, in which case you can throw an Exception as @AndrewEisenberg mentioned in his reply.


yep getClass() returns the class object of the instance with everything you need

for example getClass().getConstructors() returns a array of constructor objects which you can call

however it is impossible to know which one is invoked for a particular object unless you know more about the code inside the constructors

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜