Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
445 views
in Technique[技术] by (71.8m points)

generics - Is there a way to say "method returns this" in Java?

Is there a way to say "this method returns this" using Generics?

Of course, I want to override this method in subclasses, so the declaration should work well with @Override.

Here is an example:

class Base {
    public Base copyTo (Base dest) {
        ... copy all fields to dest ...
        return this;
    }
}
class X extends Base {
    @Override
    public X copyTo (X dest) {
        super.copyTo (dest);
        ... copy all fields to dest ...
        return this;
    }
}

public <T extends Base> T copyTo (Base dest) doesn't work at all: I get "Type mismatch: Can't convert from Base to T". If I force it with a cast, the override fails.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can do something very clever (and akin to what they have done in Scala with the 2.8 collection framework). Declare some interface method that should return "itself" (Note: This is a type parameter, not a keyword!)

public interface Addable<T, This extends Addable<T, This>> {
   public This add(T t);
}

Now declare a level of indirection - a "template" class

public interface ListTemplate<A, This extends ListTemplate<A, This>> 
    extends Addable<A, This>{
}

public interface List<A> extends ListTemplate<A, List<A>> {
}

Then an implementation of List has to return a List from the add method (I'll let you fill in the impl details)

public class ListImpl<A> implements List<A> {

    public List<A> add(A a) {
        return ...
    }
}

Similarly you could have declard a SetTemplate and a Set to extend the Addable interface - the add method of which would have returned a Set. Cool, huh?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...