Java 有没有好办法将方法声明为“returnthis”?
大概是这样的:Java 有没有好办法将方法声明为“returnthis”?,java,design-patterns,generics,java-7,crtp,Java,Design Patterns,Generics,Java 7,Crtp,大概是这样的: class C { typeof(this) foo() { return this; } } class Entity { typeof(this) refresh(); typeof(this) clone(); typeof(this) detach(); } class FooEntity extends Entity { @Override typeof(this) detach() {
class C {
typeof(this) foo() { return this; }
}
class Entity {
typeof(this) refresh();
typeof(this) clone();
typeof(this) detach();
}
class FooEntity extends Entity {
@Override
typeof(this) detach() {
fooLink21.removeRef(this);
bar39.detach();
return this;
}
void doSomeInteresting() {}
}
fooEntity.clone().detach().doSomeInteresting();
class Parent<C extends Parent> {
public C getMe (){
return this;
}
}
class Sub extends Parent<Sub> { }
嗯,我知道在Java6中这是不可能的,所以如果我能在Java7中做到这一点,我将非常高兴
编辑
这对于链接方法调用应该很有用,并避免创建临时局部变量,如:
class C {
typeof(this) foo() { return this; }
}
class Entity {
typeof(this) refresh();
typeof(this) clone();
typeof(this) detach();
}
class FooEntity extends Entity {
@Override
typeof(this) detach() {
fooLink21.removeRef(this);
bar39.detach();
return this;
}
void doSomeInteresting() {}
}
fooEntity.clone().detach().doSomeInteresting();
class Parent<C extends Parent> {
public C getMe (){
return this;
}
}
class Sub extends Parent<Sub> { }
还有更多
我认为将这个函数添加到编译器应该很容易,也许我应该入侵openjdk或gcj
顺便说一句,我从未成功地重建过openjdk。我对Java知之甚少(SD二年级学生主要使用C++),但您可能想看看泛型。如果它们是我认为它们与C++、C语言相关的,它们就像模板,可以编写返回模板类型的方法。
如果使用泛型,它可能看起来有点像这样:
class C {
typeof(this) foo() { return this; }
}
class Entity {
typeof(this) refresh();
typeof(this) clone();
typeof(this) detach();
}
class FooEntity extends Entity {
@Override
typeof(this) detach() {
fooLink21.removeRef(this);
bar39.detach();
return this;
}
void doSomeInteresting() {}
}
fooEntity.clone().detach().doSomeInteresting();
class Parent<C extends Parent> {
public C getMe (){
return this;
}
}
class Sub extends Parent<Sub> { }
类父类{
公共C getMe(){
归还这个;
}
}
类子扩展父{}
它可能会工作,但我不建议编写这样的代码。这是一个糟糕的设计…从看起来你在做的事情来看,为什么不使用构造函数呢?您可能还会问如何返回方法?如果是:
您可以返回Java中的方法。我强烈建议你不要考虑这种做法。看一看,;提供对方法、字段和构造函数的访问。Java不是用来处理一流函数的。如果您确实决定这样做,请为大量catch语句做好准备…我认为在Java6或Java7中没有任何方法可以做到这一点。添加它并不容易——我认为返回类型将是所谓的“依赖类型”,这是一个比Java目前拥有的复杂得多的类型系统 据我所知,Gressie关于向基类添加类型参数的回答是接近您想要的唯一方法 但是,如果准备使用helper函数,则可以在类上不使用类型参数:
abstract class Entity {
public static <T extends Entity> T detach(T entity) {
entity.detach();
return entity;
}
protected abstract void detach();
}
但是,这很麻烦。您是否试图避免在每个子类中重写该方法?为什么不声明一个Interace并使您的方法返回接口的子类型。您到底想实现什么?没有什么可以阻止对象返回“this”,尽管您为什么要这样做仅限于一些场景(主要是fluent builders,IMO)。
T foo(){return this;}
这就是您想要的吗?很难从问题中确定。正如您所说,这是一个糟糕的设计,它迫使您向所有类添加类型参数。客户端代码实际使用的类不需要类型参数,如本例所示。(我会把作为父级抽象。)同意,但我并不期望Java7支持它+1“静态助手”是个好主意。我原以为格雷西的主意更好,但嘿,对你有用的都可以。