Java:使用“this”作为实例方法的参数/参数名称? [英] Java: Using "this" as an argument/parameter name of an instance method?

查看:833
本文介绍了Java:使用“this”作为实例方法的参数/参数名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近从这个问题我了解到以下似乎是合法的java:

Recently from this question I have learned that the following appears to be legal java:

class Bar {
    void foo(Bar this) {}
}

现在,我试图找到java标准中的哪个位置表明你可以这样做,并且看了这里但我找不到该部分。

Now, I have tried to find where in the java standard it says that you are allowed to do this, and looked here but I couldn't find the section.

有人可以引用它允许这种形式的方法声明,以及声明名为这个的参数的限制是什么?

Can someone quote where it allows this form of method declaration and what the restrictions of declaring an argument named this are?

推荐答案

它适用于1.8或以上的JDK版本。

It is valid with 1.8 or above JDK versions.

和这是 JLS说的


receiver参数是一个可选的syntacti c实例方法的设备或内部类的构造函数。对于实例方法,receiver参数表示调用该方法的对象。对于内部类的构造函数,receiver参数表示新构造的对象的直接封闭实例。无论哪种方式,接收器参数仅用于允许在源代码中表示所表示对象的类型,以便可以对类型进行注释。

The receiver parameter is an optional syntactic device for an instance method or an inner class's constructor. For an instance method, the receiver parameter represents the object for which the method is invoked. For an inner class's constructor, the receiver parameter represents the immediately enclosing instance of the newly constructed object. Either way, the receiver parameter exists solely to allow the type of the represented object to be denoted in source code, so that the type may be annotated.

如果您阅读了完整的要点,则可以找到以下注释,

If you read full bullet points you find the below imp notes,


允许接收器参数,其类型和名称指定如下:

Where a receiver parameter is allowed, its type and name are specified as follows:




  • 在实例方法中,类型receiver参数必须是声明方法的
    类或接口,接收器参数的
    名称必须是这个;否则,发生编译时错误

    在内部类的构造函数中,接收器参数的类型
    必须是类或接口,它是内部类的立即封闭的
    类型声明,接收器
    参数的名称必须是Identifier。这里标识符是类或接口的简单
    名称,它是内部类的立即封闭的
    类型声明;否则,发生编译时错误

    这篇关于Java:使用“this”作为实例方法的参数/参数名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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