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.

Stuart
  • 286
  • 2
  • 14
  • 1
    static...abstract...whoever authored the class clearly does not want you to have an instance of it. – user1329572 Jul 07 '12 at 21:04
  • what kind of task requires to make an instance of an abstract class? –  Jul 07 '12 at 21:05
  • Abstract and static are not recommended together... You should take a look to this link: http://stackoverflow.com/questions/370962/why-cant-static-methods-be-abstract-in-java – Yannick Loriot Jul 07 '12 at 21:14
  • 2
    [Documentation](http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html): 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. – Francisco Spaeth Jul 07 '12 at 21:14
  • 2
    @YannickL. That question is about an abstract static method, this is about an abstract static inner class. – David Conrad Jul 07 '12 at 21:51

3 Answers3

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.

ManMohan Vyas
  • 4,004
  • 4
  • 27
  • 40
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);
Pshemo
  • 122,468
  • 25
  • 185
  • 269
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?

Community
  • 1
  • 1
User
  • 31,811
  • 40
  • 131
  • 232
  • Just wanted to say the same thing. All that's missing is a semicolon. – Axel Jul 07 '12 at 21:24
  • Maybe he already knows that and he just want to know if it's also possible using reflection... But wrote it for the case... – User Jul 07 '12 at 21:26
  • Yes, but more interesting would be a real world use case for this. – Axel Jul 07 '12 at 21:29