【发布时间】:2013-09-25 22:47:32
【问题描述】:
我有这个(简化的)java 接口
public interface MyInterface<T> {
public String run( T arg );
}
以及一些实现该接口的类,即
public final class SomeImplementation1 implements MyInterface<String> {
@Override
public String run( String arg) {
// do something with arg and return a string
}
}
和
public final class SomeImplementation2 implements MyInterface<CustomClass> {
@Override
public String run( CustomClass arg) {
// do something with arg and return a string
}
}
现在,我有一个用于所有这些实现的全局资源管理器,它将所有这些实现实例化到一个列表中以供以后使用。我想要实现的是这样的,这显然给了我一个错误
public final class MyInterfaceManager {
private List<MyInterface<?>> elements = new List<MyInterface<?>>();
public MyInterfaceManager() {
elements.put( new SomeImplementation1() );
elements.put( new SomeImplementation2() );
// more implementations added
}
// this is what I would like to achieve
public <T> void run( T arg ) {
for( MyInterface<?> element: elements ) {
String res = element.run( arg ); // ERROR
}
}
}
因为“arg 无法通过方法调用转换转换为 ? 的 capture#1”。
一个可能的解决方案是在循环内执行instanceof 测试,并将元素与参数一起转换为其真实类型,就像这样
public <T> void run( T arg ) {
for( MyInterface<T> element: elements ) {
if (element instanceof SomeImplementation2) {
String res = ((SomeImplementation2)element).run( (CustomClass)arg );
} else if // other tests here ...
}
}
但我不喜欢它,它一点也不优雅,它迫使我做很多instanceof 和演员表。
所以,我想知道是否有更好的方法来实现这一点。
谢谢你的帮助:)
【问题讨论】:
-
您将
getClass类型方法添加到interface中,然后简单地检查assignableFrom中List中的每个实例以查看传入的参数是否可以安全地转换为所需的参数,然后你Class.cast进行转换。 -
@BoristheSpider 谢谢你的建议,我明天试试,因为这里有点晚了:)
-
@BoristheSpider 你应该这样回答。