カスタム注釈エッセイ

3951 ワード

  java             ,          spring,   xml    annotation,          springcloud   springboot            。   springboot           ,       ,          annotation。  annotation        !

カスタム注釈の作成
カスタム注釈を作成するには、前に書いたインタフェースと同様に簡単です.インタフェースに@文字を追加するだけで、注釈クラスを作成できます.
@Retention(RetentionPolicy.RUNTIME) //    ,         。    :1、source:    ,         。2、class:Class  ,    java          .class  3、Runtime:jvm Class          ,         
@Target(ElementType.TYPE)  //       。  :java class        ,interface       ,Enum       ,@interface       
public @interface MyAnnotation {

}
  • 私たちが作成したカスタム注釈は、私たちがClassを作成したのと同じです.そのため、javaのクラスはTypeを使用し、Class、Annotation、Enum、interfaceを表すことができます.
  • @Retention(RetentionPolicy.RUNTIME)はこの注釈の宣言周期を表し、1つの注釈オブジェクトのライフサイクルには3種類のSOURCE、CLASS、RUNTIMEがあり、souceは注釈のライフサイクルがソースコード段階であることを示し、classは注釈のライフサイクルがjvmでソースコードをコンパイルすることを示す.class段階、runtimeは注釈のライフサイクルをjvmと表す.classファイルをメモリにロード(反射を使用するには、注記のライフサイクルをruntimeとして宣言する必要があります)
  • @Target(ElementType.TYPE)は、フィールドField,Class,注釈,メソッドなどの注釈作用の範囲を表す.
    カスタム注釈の使用
                    Type,         。
    
    package com.cony.annotation.demo01;
    /**
     * @author Kang
     * @date  2018 4 20    8:46:58 
     * @desciption: 
     */
    @MyAnnotation
    public class Person {
        private String userName;
        private Integer age;
        public String getUserName() {
            return userName;
        }
        public void setUserName(String userName) {
            this.userName = userName;
        }
        public Integer getAge() {
            return age;
        }
        public void setAge(Integer age) {
            this.age = age;
        }
    
    }
    

    簡単なテスト
    package com.cony.annotation.demo01;
    /**
     * @author Kang
     * @date  2018 4 20    8:49:56 
     * @desciption: 
     */
    public class PersonTest {
        public static void main(String[] args) {
            Person person=new Person();
            if(person.getClass().isAnnotationPresent(MyAnnotation.class)){//   getClass()   jvm  .class         , MyAcnnotation      runtime,     true
                MyAnnotation annotation = person.getClass().getAnnotation(MyAnnotation.class);
                System.out.println(annotation);
            }
        }
    }