private static Importable getRightInstance(String s) throws Exception {
Class c = Class.forName(s).asSubclass(Importable.class);
Importable i = c.newInstance();
return i;
}
which i can also write
private static Importable getRightInstance(String s) throws Exception {
Class<? extends Importable> c = (Class<? extends Importable>)Class.forName(s);
Importable i = c.newInstance();
return i;
}
or
private static Importable getRightInstance(String s) throws Exception {
Class<?> c = Class.forName(s);
Importable i = (Importable)c.newInstance();
return i;
}
where Importable is an interface and s is a string representing an implementing class.
Well, in any case it gives the following:
Exception in thread "main" java.lang.IncompatibleClassChangeError: class C1 has
interface Importable as super class
Here is the last snippet of the stack trace:
at java.lang.Class.forName(Class.java:169)
at Importer.getRightImportable(Importer.java:33)
at Importer.importAll(Importer.java:44)
at Test.main(Test.java:16)
Now, class C1 actually implemens Importable and i totally don’t understand why it complaints.
Thanks in advance.
IncompatibleClassChangeErrormeans something is wrong with the class file that you’re loading. In this case, it sounds likeImportablewas originally a class whenC1was compiled, and now you’ve changed it to an interface. Since the JVM cares about the difference betweenextends SomeClassandimplements SomeInterface, you’ll need to recompileC1against the currentImportableinterface (and probably also change its code fromextendstoimplements.