Any good way to declare method as `return this`?
Something like this:
class C 开发者_开发问答{
typeof(this) foo() { return this; }
}
Well, I know it's impossible in Java 6, so I'll be glad to hear if I can do it in Java 7.
EDIT
This should be useful for chaining method calls, and avoid to create temporary local variables, like 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();
and lot more.
I deem it should be very easy to add this function to compiler, well maybe I should hack into openjdk or gcj maybe?
BTW, I had never succeeded to rebuild the openjdk.
If you would use generics it might look a little bit like this:
class Parent<C extends Parent> {
public C getMe (){
return this;
}
}
class Sub extends Parent<Sub> { }
It might work, but I wouldn't suggest writing code like this. It's bad design...
I don't think there's any way to do this, in either Java 6 or Java 7. Adding it would not be easy - i think the return type would be what's called a 'dependent type', and that's something from a far more complicated type system than Java has at present.
Gressie's answer about adding a type parameter to the base class is the only way to get close to what you want, as far as i know.
However, if you were prepared to use a helper function, you could do it without a type parameter on the class:
abstract class Entity {
public static <T extends Entity> T detach(T entity) {
entity.detach();
return entity;
}
protected abstract void detach();
}
You could then say:
import static Entity.detach;
detach(fooEntity).doSomeInteresting();
That's pretty clunky, though.
I do not know much about Java (Second year SD student using primarily C#/C++), but you may want to look at Generics. If they are what I think they are in relation to C++, C#, they are like Templates, where you can write methods that return a Template type.
http://en.wikipedia.org/wiki/Generics_in_Java
From what it looks like you are doing, why not use a constructor? It also looks like you may be asking how to return a method? If so:
You can return a method in Java. I highly suggest you don't and consider alternatives to this practice. Have a look at java.lang.reflect ; provides access to methods, fields and constructors. Java is not 'meant' to deal with first-class functions. If you DO decide to do this, be prepared for a lot of catch statements...
精彩评论