In the following code, I am getting java.lang.InstantiationException
(Below is trimmed down code that compiles standalone – in my application I want to maintain an Enum->Class map, and on reading integer values from a file, instantiate appropriate class looking into the map).
How to get rid of the error? Is there a syntax problem? Must I use Interfaces? My understanding here is limited.
class Main {
abstract class Base {
Base() {};
void print() {
System.out.println("I am in Base");
}
}
class D1 extends Base {
D1() {};
@Override
void print() {
System.out.println("I am in D1");
}
}
static Class<? extends Base> getMyClass() {
return D1.class;
}
public static void main(String[] args) {
try {
Class<?> cc = getMyClass();
Object oo = cc.newInstance();
Base bb = (Base) oo;
bb.print();
} catch (Exception ee) {
System.out.println(ee);
};
}
};
Your code has two problems:
BaseandD1are non-static inner classes. It means that they can access fields and methods of their declaring class (Main), therefore they should hold a reference to the instance ofMain. Therefore their constructors have an implicit argument of typeMainwhich is used to pass that reference. So, they don’t have no-args constructors and you should use a single-argument constructor instead:Alternatively, you can simply declare them as
static, or declare them outside ofMain– in this case they won’t be able to access member ofMainand won’t require a reference to it.Constructor of
D1should bepublic. Otherwise you need to callsetAccessible(true)to make it accessible for reflection.