对可能实现该接口的对象调用具有接口约束的泛型方法 [英] Call generic method with interface constraints on objects who may implement that interface
本文介绍了对可能实现该接口的对象调用具有接口约束的泛型方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我的代码:
接口a {}
class b {}
class c扩展b实现一个{}
class d extends b {}
class e {
public void makeItWork(){
b [] bees = new b [] {new c() ,new d()}; (b bee:bees){
if(bee instanceof a){
a beeA =(a)bee;
//如果对象蜜蜂符合接口,如何调用方法测试?
test(beeA.getClass(),beeA);
//这是错误的
}
}
}
public< T extends a> void test(Class< T> classType,T concrete){
}
}
<除了可能是坏的设计,我想知道是否可以在实现接口 a 的对象上调用方法
test
code>。
解决方案
您的 test
方法不会需要一个泛型类型参数。
您可以将其定义为:
public void test(Class< ;? extends a> classType,具体){
}
PS请使用大写的类名。
This is my code:
interface a {}
class b{}
class c extends b implements a{}
class d extends b{}
class e{
public void makeItWork(){
b[] bees = new b[] {new c(), new d()};
for (b bee: bees){
if (bee instanceof a) {
a beeA = (a) bee;
//how to call the method test if object bee conforms the the interface?
test(beeA.getClass(), beeA);
//this goes wrong
}
}
}
public <T extends a> void test(Class<T> classType, T concrete){
}
}
Besides maybe the bad design, I would like to know if it is possible to call the method test
on objects who implements the interface a
.
解决方案
your test
method doesn't need a generic type parameter.
You can define it as:
public void test(Class<? extends a> classType, a concrete) {
}
P.S. please use capitalized class names.
这篇关于对可能实现该接口的对象调用具有接口约束的泛型方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文