I'd like to create a registry for classes which are subclasses of a super class. The classes are stored in a map which acts as registry. A class is picked from the registry depending on a key and an instance of that class will be created via reflection.
I'd like to instantiate a class depending on a constructor (with 1 parameter) of the super class. It works only if I declare the constructor in the subclasses as well.
Is there a way to instantiate the class using a constructor of a super class? Is there a way to make that code type-safe?
Example code:
public class ReflectionTest {
/**
* Base class with no-args constructor and another constructor with 1 parameter
*/
public static class BaseClass {
Object object;
public BaseClass() {
System.out.println("Constructor with no args");
}
public BaseClass( Object object) {
this.object = object;
System.out.println("Constructor with parameter= " + object);
}
public String toString() {
return "Object = " + object;
}
}
/**
* Subclass with 1 parameter constructor
*/
public static class SubClass1 extends BaseClass {
public SubClass1( Object object) {
super(object);
}
}
/**
* Subclass with no-args constructor
*/
public static class SubClass2 extends BaseClass {
}
public static void main(String[] args) {
// registry for classes
Map<Integer,Class<?>> registry = new HashMap<>();
registry.put(0, SubClass1.class);
registry.put(1, SubClass2.class);
// iterate through classes and create instances
for( Integer key: registry.keySet()) {
// get class from registry
Class<?> clazz = registry.get(key);
try {
// get constructor with parameter
Constructor constructor = clazz.getDeclaredConstructor( Object.class);
// instantiate class
BaseClass instance = (BaseClass) constructor.newInstance(key);
// logging
System.out.println("Instance for key " + key + ", " + instance);
} catch (NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
e.printStackTrace();
}
}
System.exit(0);
}
}
The example gives the following console output:
Constructor with parameter= 0
Instance for key 0, Object = 0
java.lang.NoSuchMethodException: swing.table.ReflectionTest$SubClass2.<init>(java.lang.Object)
at java.lang.Class.getConstructor0(Class.java:3082)
at java.lang.Class.getConstructor(Class.java:1825)
at swing.table.ReflectionTest.main(ReflectionTest.java:63)