Javagenerics强制执行抽象方法的返回类型
我有以下情况:
abstract class X { abstract X someMethod (...) {...} }.
现在我想约束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
是否有可能使用Javagenerics实现这一点?
编辑
好的。 我只问了是/否问题并得到了“是”。 我的错。 我真正感兴趣的是“我如何编写声明”。
这也有效;
abstract class X { public abstract T yourMethod(); } class X1 extends X { public X1 yourMethod() { return this; } } class X2 extends X { public X2 yourMethod() { return this; } }
abstract class X> { protected X(Class implClazz) { if (!getClass().equals(implClazz)) { throw new IllegalArgumentException(); } } abstract I someMethod(); }
基本原理:您不能在类型边界中引用动态类型,因此在构造函数中间接检查。
这是一种允许您this
返回参数类型的方法:
AbstractFoo> { /** 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(); } }
是。 这是返回类型的协方差 。
这应该工作得很好:
class X { abstract T someMethod(...); } class X1 extends X T1 someMethod(...) { ... } }