zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    软件工程2019实践第一次作业
    Maven环境的搭建
    TomCat控制台中文乱码及IDEA设置为UTF-8
    将win10永久激活为专业工作站版(图文详细教程)
    [软件技巧]manjaro gnome中修改屏幕缩放比例
    第一次个人编程作业
    百度的TTS API
    第一次软件工程实践作业
    MySQL触发器的操作
    Anaconda使用conda activate激活环境报错Your shell has not been properly configured to use 'conda activate'.
  • 原文地址:https://www.cnblogs.com/strongmore/p/15083069.html
Copyright © 2011-2022 走看看