1

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.

5
  • 1
    static...abstract...whoever authored the class clearly does not want you to have an instance of it. Commented Jul 7, 2012 at 21:04
  • what kind of task requires to make an instance of an abstract class? Commented Jul 7, 2012 at 21:05
  • Abstract and static are not recommended together... You should take a look to this link: stackoverflow.com/questions/370962/… Commented Jul 7, 2012 at 21:14
  • 2
    Documentation: An abstract class is a class that is declared abstract—it may or may not include abstract methods. Abstract classes cannot be instantiated, but they can be subclassed. Commented Jul 7, 2012 at 21:14
  • 2
    @YannickL. That question is about an abstract static method, this is about an abstract static inner class. Commented Jul 7, 2012 at 21:51

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

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?

3 Comments

Just wanted to say the same thing. All that's missing is a semicolon.
Maybe he already knows that and he just want to know if it's also possible using reflection... But wrote it for the case...
Yes, but more interesting would be a real world use case for this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.