Hi, this code doesn't compile. I'm wondering what I am doing wrong:
private static Importable getRightInstance(String s) throws Exception {
Class<Importable> c = Class.forName(s);
Importable i = c.newInstance();
return i;
}
where Importable is an interface and the string s is the name of an implementing class. The compiler says:
./Importer.java:33: incompatible types
found : java.lang.Class<capture#964 of ?>
required: java.lang.Class<Importable>
Class<Importable> c = Class.forName(format(s));
thanks for any help!
All the solutions
Class<? extends Importable> c = Class.forName(s).asSubclass(Importable.class);
and
Class<? extends Importable> c = (Class<? extends Importable>) Class.forName(s);
and
Class<?> c = Class.forName(format(s));
Importable i = (Importable)c.newInstance();
give this error (that i don't understand):
Exception in thread "main" java.lang.IncompatibleClassChangeError: class C1
has interface Importable as super class
where C1 is actually implementing Importable (so it is theoretically castable to Importable).