[英]Java Generic Interface Return Type
Migrating to Java from C++. 从C ++迁移到Java。
I have a third party code with an interface I am required to implement which goes something like this. 我有一个第三方代码,该接口需要实现这样的接口。
public interface Foo<T>{
public T doSomething();
}
I want to implement this interface so that I can call doSomething() and get 3 different classes A, B and C
which extend a common base Z
as below. 我想实现此接口,以便可以调用doSomething()并获得3个不同的类A, B and C
,它们扩展了如下所示的公共基数Z
public class A extends Z{...};
public class B extends Z{...};
public class C extends Z{...};
I could not find any way of avoiding writing the following 3 classes. 我无法避免避免编写以下3个类。
public class ARet implements Foo<A>{...}
public class BRet implements Foo<B>{...}
public class CRet implements Foo<C>{...}
For the given interface Foo
, is it not possible to write an implementation which returns T extends Z
something which would look like public class Ret implements Foo<T extends Z>{...}
. 对于给定的接口Foo
,不可能编写一个返回T extends Z
的实现,该实现类似于public class Ret implements Foo<T extends Z>{...}
。 This does not appear to work. 这似乎不起作用。 Is there any way of avoiding the 3 classes or there is no way around it? 有什么办法可以避免这三类,还是没有办法解决?
如果要使接口的实现通用,则需要将T声明为Ret的通用类型参数:
public class Ret<T extends Z> implements Foo<T>{...}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.