我正在玩
Java的Reflection.我有一个带有构造函数的抽象类Base.
abstract class Base { public Base( String foo ) { // do some magic } }
我还有一些扩展Base的类.它们没有太多逻辑.我想用Base的构造函数实例化它们,而不必在这些派生类中编写一些代理构造函数.当然,我想用Reflection实例化那些派生类.说:
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