pnt*_*pnt 8 java generics inheritance
我正面临这个问题中描述的问题,但想找到一个没有所有演员和@SuppressWarning注释的解决方案(如果可能的话).
一个更好的解决方案是建立在引用的解决方案之上:
此处提供的解决方案将根据标准评分为2分.Bounty用大多数积分去解决方案,或者如果有多个积分,那么"最优雅的"积分将达到2分.
没有演员阵容,没有@SuppressWarning,只有几行:
public abstract class SuperClass<T extends SuperClass<T>> {
protected T that;
public T chain() {
return that;
}
}
public class SubClass1 extends SuperClass<SubClass1> {
public SubClass1() {
that = this;
}
}
public class SubClass2 extends SuperClass<SubClass2> {
public SubClass2() {
that = this;
}
}
Run Code Online (Sandbox Code Playgroud)
一种方法是getThis()在Parent类中定义一个抽象方法,并使所有Child类覆盖它,返回this引用.这是一种恢复this类层次结构中对象类型的方法.
代码如下所示:
abstract class Parent<T extends Parent<T>> {
protected abstract T getThis();
public T example() {
System.out.println(this.getClass().getCanonicalName());
return getThis();
}
}
class ChildA extends Parent<ChildA> {
@Override
protected ChildA getThis() {
return this;
}
public ChildA childAMethod() {
System.out.println(this.getClass().getCanonicalName());
return this;
}
}
class ChildB extends Parent<ChildB> {
@Override
protected ChildB getThis() {
return this;
}
public ChildB childBMethod() {
return this;
}
}
public class Main {
public static void main(String[] args) throws NoSuchMethodException {
ChildA childA = new ChildA();
ChildB childB = new ChildB();
childA.example().childAMethod().example();
childB.example().childBMethod().example();
}
}
Run Code Online (Sandbox Code Playgroud)
根据要求,没有Casting,也没有@SuppressWarnings.几天前我从Angelika Langer - Java Generics常见问题解答中学到了这个技巧.
参考: