Accessing constructor from abstract base class with reflection

Posted by craesh on Stack Overflow See other posts from Stack Overflow or by craesh
Published on 2011-01-13T16:46:31Z Indexed on 2011/01/13 16:53 UTC
Read the original article Hit count: 300

Filed under:
|
|

Hi!

I'm playing around with Java's Reflection. I have an abstract class Base with a constructor.

abstract class Base {
    public Base( String foo ) {
        // do some magic
    }
}

I have some further classes extending Base. They don't contain much logic. I want to instantiate them with Base's constructor, without having to write some proxy contructors in those derived classes. And of course, I want to instantiate those derived classes with Reflection. Say:

Class cls = SomeDerivedClass.class;
Constructor constr;
constr = cls.getConstructor( new Class[] { String.class } ); // will return null
Class clsBase = Base.class;
constr = clsBase.getConstructor( new Class[] { String.class } ); // ok
Base obj = (Base) constr.newInstance( new Object[] { "foo" } ); // will throw InstantiationException because it belongs to an abstract class

Any ideas, how I can instantiate a derived class with Base's constructor? Or must I declare those dumb proxy constructors?

© Stack Overflow or respective owner

Related posts about java

Related posts about reflection