我正面临this question中描述的问题,但想找到一个没有所有演员表和@SuppressWarning注释的解决方案(如果可能的话)。
更好的解决方案是建立在引用的解决方案之上:
此处提供的解决方案将根据标准评分为2分。 Bounty可以解决大多数积分或“最优雅”积分,如果有多个积分,则为2分。
答案 0 :(得分:9)
没有演员阵容,没有@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;
}
}
答案 1 :(得分:5)
一种方法是在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();
}
}
根据要求,没有 Casting 且没有 @SuppressWarnings 。几天前我从Angelika Langer - Java Generics FAQs学到了这个技巧。
<强>参考:强>
答案 2 :(得分:1)
一种解决方案是覆盖子类中的方法,并将返回类型更改为更具体的方法,即。孩子的类型。这需要铸造。请使用Class#cast(Object)
方法
(Child)
广告
public class Parent {
public Parent example() {
System.out.println(this.getClass().getCanonicalName());
return this;
}
}
public class Child extends Parent {
public Child example() {
return Child.class.cast(super.example());
}
public Child method() {
return this;
}
}
演员表隐藏在标准方法中。来自Class
。
public T cast(Object obj) {
if (obj != null && !isInstance(obj))
throw new ClassCastException(cannotCastMsg(obj));
return (T) obj;
}