I'm trying to create an object of a class, using just a name of this clas开发者_StackOverflow社区s:
public interface Foo {
}
public class Bar implements Foo {
}
[...]
Class<Foo> c = Class.forName("com.XXX.Bar").asSubclass(Foo.class);
Foo foo = c.newInstance();
Compiler says:
incompatible types found :
java.lang.Class<capture#47 of ? extends com.XXX.Foo>
required: java.lang.Class<com.XXX.Foo>
What's wrong here?
Since c
is a some class which extends Foo
, you should express it in the code using <? extends ...>
syntax:
Class<? extends Foo> c = Class.forName("com.XXX.Bar").asSubclass(Foo.class);
精彩评论