有没有办法说“方法返回这个”在Java中? [英] Is there a way to say "method returns this" in Java?

查看:95
本文介绍了有没有办法说“方法返回这个”在Java中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法说这个方法返回这个使用泛型?



当然,我想要在子类中覆盖这个方法,所以声明应该可以很好地适用于 @Override



这里是一个例子:

  class Base {
public Base copyTo(Base dest){
... copy all fields到dest ...
返回这个;
}
}
class X extends Base {
@Override
public X copyTo(X dest){
super.copyTo(dest);
...将所有字段复制到dest ...
返回此;


$ / code $ / pre

public< T extends基> T copyTo(Base dest)根本不起作用:Type mismatch:Can not convert from Base to T。如果我用强制强制它,重写失败。

解决方案

不,没有办法表达它。只需声明返回类的类型的方法即可。 Java有协变的返回类型,所以你可以重写一个方法来返回一个更具体的类型。

如果你想为这个标记,你可以随时引入你的自己的注释 - 但不要指望任何其他工具采取任何特别注意它。



编辑:从oxbow_lakes的答案确实会给大多数情况下工作的东西,但我相信有很多方法可以让你愚弄它,以至于你实际上正在处理不同的类型。 (无论如何,从实验记忆来看)。请注意,这与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.

解决方案

No, there's no way of expressing that. Just declare the method to return the type of the class. Java has covariant return types, so you can override a method to return a more specific type anyway.

If you wanted to have some marker for this, you could always introduce your own annotation - but don't expect any other tools to take any particular notice of it.

EDIT: the answer from oxbow_lakes does indeed give something which will work in most cases, but I believe there are ways of fooling it such that you're actually dealing with a different type. (From memories of experimentation, anyway.) Note that this is similar to how Java enums work.

这篇关于有没有办法说“方法返回这个”在Java中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆