[英]Can't pass implementation to method declaring generic interface (Java)
Two attempts at passing in my generic class in the MyTest class below. 两次尝试在下面的MyTest类中传递我的通用类。 The Strategy hierarchy seems fine, but declaring methods with the generic interface as an argument has problems.
策略层次结构看起来不错,但是使用通用接口作为参数声明方法存在问题。 How do I resolve this?
我该如何解决?
interface Node {}
class NodeImpl implements Node {}
interface Strategy <N extends Node> {
void setNode(N node);
}
class MyStrategy implements Strategy<NodeImpl> {
@Override
public void setNode(NodeImpl node) {
}
}
class MyTest {
void test1(Strategy<? extends Node> s) {
s.setNode(new NodeImpl()); // compile error
}
void test2(Strategy<Node> s) {
s.setNode(new NodeImpl());
}
void v() {
test1(new MyStrategy());
test2(new MyStrategy()); // compile error
}
}
Test1 compile error: The method setNode(capture#1-of ? extends Node) in the type Strategy is not applicable for the arguments (NodeImpl) Test1编译错误:策略类型中的方法setNode(capture#1-of扩展Node)不适用于参数(NodeImpl)
Test 2 compile error: The method test2(Strategy) in the type MyTest is not applicable for the arguments (MyStrategy) 测试2编译错误:MyTest类型的方法test2(Strategy)不适用于自变量(MyStrategy)
The MyTest class is part of an inheritance hierarchy, I wish to keep the test1() or test2() method generic, being able to pass in any Strategy implementation MyTest类是继承层次结构的一部分,我希望保持test1()或test2()方法的通用性,使其能够传入任何Strategy实现中
test1 and test2 can compile if you use NodeImpl
instead of Node (generics is strongly typed). 如果您使用
NodeImpl
而不是Node(泛型是强类型的),则test1和test2可以编译。 About Test1, as per Marko suggestion, you should use Strategy <? super NodeImpl>
关于Test1,按照Marko的建议,您应该使用
Strategy <? super NodeImpl>
Strategy <? super NodeImpl>
into method signature. Strategy <? super NodeImpl>
转换为方法签名。
This appears to solve the problem, but it's a bit clunky. 这似乎可以解决问题,但是有点笨拙。 I'm also interested in any design comments within the scope of this example code.
我也对此示例代码范围内的任何设计注释感兴趣。
interface Node {}
class NodeImpl implements Node {}
interface Strategy <N extends Node> {
void setNode(N node);
Class<N> getType();
}
class MyStrategy implements Strategy<NodeImpl> {
@Override
public void setNode(NodeImpl node) {
}
@Override
public Class<NodeImpl> getType() {
return NodeImpl.class;
}
}
class MyTest {
<T extends Node> void test3(Strategy<T> s) {
s.setNode(s.getType().cast(new NodeImpl()));
}
void v() {
test3(new MyStrategy());
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.