[英]Implements an interface that return a generic type
I saw these:我看到了这些:
I do understand why the compilator complains.我确实理解编译器为什么会抱怨。
Anyway, if we only use the generic as a return value.无论如何,如果我们只使用泛型作为返回值。
public interface Connection
{
<T extends Comparable<? super T>> T getVersion();
}
Then this implementation only gives a warning (I am using Java 7):然后这个实现只给出一个警告(我使用的是 Java 7):
public class IoConnectionStub implements Connection
{
public String getVersion()
{
return "1.0";
}
}
Is this valid ?这是有效的吗? Or will it cause some problems ?还是会引起一些问题?
Thanks !谢谢 !
For a generic method, the caller can specify the type argument - so I should be able to use:对于泛型方法,调用者可以指定类型参数 - 所以我应该能够使用:
Connection foo = new IoConnectionStub();
Integer x = foo.<Integer>getVersion();
That's clearly not going to work in your case.这显然不适用于您的情况。
It sounds like if you really need this (which I think is slightly odd for a version property...) you would want to make the interface generic - that way IoConnectionStub
could implement Connection<String>
for example, and you'd end up with code of:听起来如果你真的需要这个(我认为这对于版本属性来说有点奇怪......)你会想要使接口通用 - 例如,这样IoConnectionStub
可以实现Connection<String>
,你最终会代码如下:
Connection<String> foo = new IoConnectionStub();
String version = foo.getVersion();
You couldn't ask for an Integer
version number, because IoConnectionStub
wouldn't implement Connection<Integer>
.您不能要求Integer
版本号,因为IoConnectionStub
不会实现Connection<Integer>
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.