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).
Try:
Here are some snippets to illustrate the problems:
However:
So for an
interface
, you definitely need the upper-bounded wildcard. TheasSubclass
is as suggested by doublep.API links
<U> Class<? extends U> asSubclass(Class<U> clazz)
Class
object to represent a subclass of the class represented by the specified class object. Checks that that the cast is valid, and throws aClassCastException
if it is not. If this method succeeds, it always returns a reference to this class object.Related questions
<E extends Number>
and<Number>
?See also
The issue is Class.forName is a static method with the following definition
public static Class forName(String className) throws ClassNotFoundException
Therefore it is not a bound parameter type at all and compiler would definitely throw the cast warning here as it has no way to guarantee the string name of the class would always give you the implementation of the interface.
If you know for sure that the string name passed into the method would be an implementation of the interface you can use SuppressWarnings annotation. But I dont think ther eis any other cleaner way to use forName with generics
Use a runtime conversion:
This will bark with an exception at runtime if
s
specifies a class that doesn't implement the interface.Something like this might do the trick:
Beware of a
ClassCastException
orNoClassDefFound
if you pass in the wrong thing. As @polygenelubricants says, if you can figure out some way to avoidClass.forName
then so much the better!The compiler can't know that, hence the error.
Use a cast. It is easier to cast the constructed object (because that is a checked cast), than the class object itself.