Why can we use 'this' as an instance metho

2019-01-13 18:31发布

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

2条回答
倾城 Initia
2楼-- · 2019-01-13 18:57

The JLS gives a hint:

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.

These two methods are equivalent:

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 {}
查看更多
我欲成王,谁敢阻挡
3楼-- · 2019-01-13 19:00

Receiver parameters allow to pass arguments and extract additional information from these arguments. The only purpose of writing the receiver explicitly is to make it possible to annotate the receiver’s type. Now, if you implement the AnnotatedElement interface, you could call the getAnnotation() method of your class to get an annotation type. For more information, you can read this.

查看更多
登录 后发表回答