为什么我们可以使用“this"作为实例方法参数? [英] Why can we use 'this' as an instance method parameter?

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

问题描述

Java 中的接收器参数是什么?Java 8 语言规范谈到了this.

What is a receiver parameter in Java ? Java 8 Language Specification talks about this.

推荐答案

JLS 给出了 提示:

无论哪种方式,接收器参数的存在都是为了允许在源代码中表示所表示对象的类型,以便可以对类型进行注释.

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.

这两种方法是等价的:

class Test {
    void m1() { }
    void m2(Test this) { }
}

但是后者允许您添加注释:

However the latter allows you to add annotations:

void m2(@MyAnnotation Test this) { }
//where MyAnnotation can be defined like this for example:
@Target(ElementType.TYPE_USE) @interface MyAnnotation {}

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

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