开发者

How to load a custom class inherited from existing one?

开发者 https://www.devze.com 2023-01-19 09:14 出处:网络
I\'m trying to create an object of a class, using just a name of this clas开发者_StackOverflow社区s:

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); 
0

精彩评论

暂无评论...
验证码 换一张
取 消