Stuart
Stuart

Reputation: 286

Creating an instance of a static abstract class with Java reflection?

I have this:

public interface Receiver extends x.y.a
{
    public static abstract class Stub extends x.y.b implements Receiver
    {
        public Stub()
        {
        }
    }
}

and want to write this:

private final Receiver receiver = new Receiver.Stub()
{
};

using reflection. Is that even possible? I can find the Stub() constuctor, but of course it fails to execute on its own.

Upvotes: 1

Views: 2208

Answers (3)

ixx
ixx

Reputation: 32269

Your code works, without reflection. You are creating an anonymous subclass. AFAIK it's not possible to create a subclass (anonymous) using reflection. Maybe this thread is informative:

In Java is it possible to dynamically create anonymous subclass instance given only instance of parent class?

or this: Is it possible to create an anonymous class while using reflection?

Upvotes: 1

Pshemo
Pshemo

Reputation: 124275

From what I know you can't create instance of abstract class. Even with reflection. If that class wasn't abstract you could simply call

Constructor c = Receiver.Stub.class.getConstructor(null);
Receiver r= (Receiver)c.newInstance(null);

Upvotes: 1

ManMohan Vyas
ManMohan Vyas

Reputation: 4062

No that is not possible, you will get exception if you try to instantiate abstract class through reflection. Whatever is the case always remember you cannot instantiate abstract class. Though you can create anonymous class.

Upvotes: 2

Related Questions