是否可以对命名泛型类型施加上限(super X)?
假设我有以下静态方法和接口(List 是 java.util.List)。请注意,静态方法在列表的通配符类型上强制使用“super Foo”。
public class StaticMethod {
public static void doSomething(List<? super Foo> fooList) {
...
}
}
public interface MyInterface<T> {
public void aMethod(List<T> aList);
}
我希望能够添加一个使用静态方法实现接口的类,如下所示:
public class MyClass<T> implements MyInterface<T> {
public void aMethod(List<T> aList) {
StaticMethod.doSomething(aList);
}
}
这显然不会编译,因为 T 没有“super Foo”约束。但是,我看不到任何添加“super Foo”约束的方法。例如 - 以下内容是不合法的:
public class MyClass<T super Foo> implements MyInterface<T> {
public void aMethod(List<T> aList) {
StaticMethod.doSomething(aList);
}
}
有没有办法解决这个问题 - 最好不改变 StaticMethod
或 MyInterface
?
Suppose I have the following static method and interface (List is java.util.List). Note that the static method enforces a "super Foo" on the wildcard type of the list.
public class StaticMethod {
public static void doSomething(List<? super Foo> fooList) {
...
}
}
public interface MyInterface<T> {
public void aMethod(List<T> aList);
}
I would like to be able to add a class which implements the interface using the static method as follows:
public class MyClass<T> implements MyInterface<T> {
public void aMethod(List<T> aList) {
StaticMethod.doSomething(aList);
}
}
This obviously won't compile because T does not have the "super Foo" constraint. However, I can't see any way of adding the "super Foo" constraint. For example - the following is not legal:
public class MyClass<T super Foo> implements MyInterface<T> {
public void aMethod(List<T> aList) {
StaticMethod.doSomething(aList);
}
}
Is there any way of solving this problem - ideally without altering StaticMethod
or MyInterface
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
发布评论
评论(2)
如果您确定 aList
包含可以安全地转换为 ,那么您可以执行以下操作:
public static class MyClass<T> implements MyInterface<T> {
@Override
public void aMethod(List<T> aList) {
StaticMethod.doSomething((List<? super Foo>) aList);
}
}
查看完整且有效的示例:http://ideone.com/fvm67
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
我在这里冒险,但我认为下界是这里的问题,因为当您引用它时,您必须知道适合该边界的实际类......您不能使用继承。
这是一个可以编译的用法,但请注意,我需要命名实际的类,该类是 Foo:
Comments?
的父类。 ps我喜欢这个问题:)
I'm going out on a limb here, but I think lower bounding is the problem here, because you have to know about the actual class that fits the bound when you refer to it... you can't use inheritance.
Here's a usage that compiles, but notice that I need to name the actual class that is a super of Foo:
Comments?
p.s. I like the question :)