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

  • 相关阅读:
    Base64 加密之中文乱码
    JAVA 笔记 ReadWriteLock
    手机上的消息推送
    Erlang 聊天室程序(九) 主题房间2 房间信息管理
    阿里云服务器上安装GCC
    jq实现窗帘式图片
    Oracle版本问题!【急急急】
    解决 VSCode git commit 时 No such file or directory 报错问题
    GIT Authentication failed for错误问题处理
    h5接入微信分享sdk,报错Cannot read property of undefined (reading 'title')
  • 原文地址:https://www.cnblogs.com/strongmore/p/15083069.html
Copyright © 2011-2022 走看看