Class<T> and static method Class.forName() drive me crazy.

Posted by matt on Stack Overflow See other posts from Stack Overflow or by matt
Published on 2010-05-23T18:06:16Z Indexed on 2010/05/23 19:20 UTC
Read the original article Hit count: 218

Filed under:
|
|

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:

Exception in thread "main" java.lang.IncompatibleClassChangeError: class C1 
has interface Importable as super class

where C1 is effectively a class implementing Importable, one of those i want to cast to Importable.

© Stack Overflow or respective owner

Related posts about java

Related posts about generics