java8新特性Receiver Parameter入门

前言

Receiver Parameter,翻译过来就是接受者参数,举一个例子

public class Person {

  public void test(Person this) {
  }

}

我们声明了一个实例方法,第一个参数为当前实例本身,这种写法和下面的写法没有什么区别

public class Person {

  public void test() {
  }

}
public class Person {

  public void test(Person this) {
  }

  public void test() {
  }

}

如果我们两种方式的方法都定义,就会编译错误,方法定义重复。那我们可以用它来干什么呢?可以进行增强的类型检查,使用注解处理器在编译时进行检查,具体定义可以查看 官方文档

import java.lang.annotation.Annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.AnnotatedType;
import java.lang.reflect.Method;

public class Person {

  public void test(@SafeObject Person this) {
  }

  public static void main(String[] args) throws NoSuchMethodException {
    Method testMethod = Person.class.getDeclaredMethod("test");
    AnnotatedType annotatedReceiverType = testMethod.getAnnotatedReceiverType();
    System.out.println(annotatedReceiverType);
    System.out.println(annotatedReceiverType.getType());
    for (Annotation annotation : annotatedReceiverType.getDeclaredAnnotations()) {
      System.out.println(annotation);
    }
  }


  @Target(ElementType.TYPE_USE)
  @Retention(RetentionPolicy.RUNTIME)
  public @interface SafeObject {

  }
}

输出为

sun.reflect.annotation.AnnotatedTypeFactory$AnnotatedTypeBaseImpl@3dd4520b
class com.imooc.sourcecode.java.base.java8.receiverparam.Person
@com.imooc.sourcecode.java.base.java8.receiverparam.Person$SafeObject()

可以通过getAnnotatedReceiverType()方法获取参数上的注解及当前实例类型。

总结

暂时还不知道此特性的使用场景,先记录下。

参考

Explicit Receiver Parameters

原文地址:https://www.cnblogs.com/strongmore/p/15083069.html