java Java泛型强制抽象方法的返回类型
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1627581/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java generics to enforce return type of abstract method
提问by Erwin Smout
I have the following situation :
我有以下情况:
abstract class X { abstract X someMethod (...) {...} }.
Now I want to constrain any implementation of X to have its 'someMethod' method return that particular implementation type, not just X :
现在我想限制 X 的任何实现,使其 'someMethod' 方法返回该特定实现类型,而不仅仅是 X :
class X1 extends X { X1 someMethod (...) {...} }.
class X1 extends X { X someMethod (...) {...} }. //want this to be flagged as an error
class X2 extends X { X1 someMethod (...) {...} }. //want this to be flagged as an error too
Is it possible to achieve this using Java generics ?
是否可以使用 Java 泛型来实现这一点?
EDIT
编辑
Okay. I only asked the yes/no question and got a "yes". My fault. What I was actually interested in is "how do I write the declarations".
好的。我只问了是/否问题,然后得到了“是”。我的错。我真正感兴趣的是“我如何编写声明”。
回答by Bj?rn
This works as well;
这也有效;
abstract class X<T> {
public abstract T yourMethod();
}
class X1 extends X<X1> {
public X1 yourMethod() {
return this;
}
}
class X2 extends X<X2> {
public X2 yourMethod() {
return this;
}
}
回答by meriton
abstract class X<I extends X<I>> {
protected X(Class<I> implClazz) {
if (!getClass().equals(implClazz)) {
throw new IllegalArgumentException();
}
}
abstract I someMethod();
}
Rationale: You can not refer to the dynamic type in type bounds, hence the indirect check in the constructor.
理由:您不能在类型边界中引用动态类型,因此在构造函数中进行间接检查。
回答by rjrjr
Here's an approach that lets you return a parameter type for this:
这是一种让您返回参数类型的方法this:
AbstractFoo<T extends AbstractFoo<T>> {
/** Subclasses must implement to return {@code this}. */
protected abstract T getThis();
/** Does something interesting and returns this Foo */
public T inheritedThing {
/* blah di blah */
return getThis();
}
}
回答by uckelman
Yes. This is return type covariance.
是的。这是返回类型协方差。
回答by Robert J. Walker
This should work just fine:
这应该工作得很好:
class X<T> {
abstract T someMethod(...);
}
class X1<T1> extends X
T1 someMethod(...) {
...
}
}

