将方法声明为`return this`的任何好方法?

Xiè*_*léi 3 java generics design-patterns crtp java-7

像这样的东西:

class C {

    typeof(this) foo() { return this; }

}
Run Code Online (Sandbox Code Playgroud)

好吧,我知道在Java 6中这是不可能的,所以我很高兴听到我是否可以在Java 7中完成它.

编辑

这对链接方法调用很有用,并且避免创建临时局部变量,如下所示:

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();
Run Code Online (Sandbox Code Playgroud)

还有更多.

我认为将此函数添加到编译器应该很容易,也许我应该入侵openjdk或者gcj?

顺便说一句,我从未成功重建openjdk.

Gre*_*sie 5

如果您使用泛型,它可能看起来有点像这样:

class Parent<C extends Parent> {

   public C getMe (){
      return this;
   }
}

class Sub extends Parent<Sub> { }
Run Code Online (Sandbox Code Playgroud)

它可能有用,但我不建议编写这样的代码.这是糟糕的设计......