Java抽象类:为派生类返回“this”指针
我试图用帮助器方法编写一些自定义exception来设置这样的变量:
public class KeyException extends RuntimeException { protected String Id; protected KeyException(String message) { super(message); } protected KeyException(String message, Throwable cause) { super(message, cause); } public String getId() { return keyId; } public KeyException withId(final String Id) { this.Id = Id; return this; } }
但是,在我的派生类中,我不能使用“withId”方法,因为它只返回基类 – 无论如何返回“this”指针而不必覆盖每个派生类中的方法?
无论如何返回“this”指针而不必覆盖每个派生类中的方法?
是的,请看下面的选项1。
您可以通过以下几种方式执行此操作:
-
将结果转换为派生类
-
在子类中重写它
-
将返回类型更改为void。 由于您在对象上调用方法,因此您已经有了指向它的指针。
你可以这样做:
public T withId(final String Id) { this.Id = Id; return (T)this; }
然后在派生类中,只需将其类型作为类型参数传递。
但是可能存在设计疏忽。 除了构建器模式,我很少看到setter返回对象本身的引用。 如果您提供更多上下文,我们将能够为您提供更多帮助。
generics使用以下构造是可能的:
public class ParentType> { public T withId(String someId) { /* Insert other code here */ return (T) this; } } public class BranchType > extends ParentType {} public final class LeafTypeA extends BranchType {} public final class LeafTypeB extends ParentType {}
其中BranchType是具有子类的类,而LeafTypeA,LeafTypeB是没有子类的类。
这比其他generics解决方案略有改进,因为它可以防止:
public class LeafTypeA extends BranchType {}
由于这不满足类型参数的约束。
如果你有派生类,例如
public class AnotherException extends KeyException { ... }
….然后你可以简单地使用withId
….
AnotherException a = new AnotherException ("A"); AnotherException b = (AnotherException) a.withId("ID");
…因为它基本上是同一个对象。 你只需要施展它。
有一种方法可以使用generics来解决返回子类问题:
// base class public class Base { private T myself; public Base(T myself, Class cls) { this.myself = myself; } public T withSomething() { return myself; } } // subclass public class SomeSubCls extends Base { public SomeSubCls() { super(this, SomeSubCls.class); } }
使用此模式new SomeSubCls().withSomething()
将返回作为子类实例的对象,而不是父对象。
例如,由fest断言使用,检查一下
不幸的是没有。 如果你能做到这一点会很好
public this withId(final String Id) { // doesn't work this.Id = Id; return this; }
要不就
public this withId(final String Id) { // doesn't work either this.Id = Id; }
或者它会知道“无效”方法是隐式链接的(因为我相信一个正式提案建议)