java之自定義註解第二篇

  • 2019 年 11 月 26 日
  • 筆記

上篇文章內容我們分享一下了自定義註解的內容,這篇文章主要分享的內容就是關於如何獲取自定義註解上面的內容。

好了,我們還是趕緊定義一個自定義註解的示常式序咯。

package com.wpw.springboot;    import java.lang.annotation.*;    @Documented  @Inherited  @Target({ElementType.FIELD})  @Retention(RetentionPolicy.RUNTIME)  public  @interface ContentAnnotation {      String value () default "111";  }  

上面註解的內容就是說你沒有給value賦值,就使用默認值111。

我們看下我們自定義註解使用的類,主要是用來做簡單的示常式序的,所以寫法也比較簡單一些。

package com.wpw.springboot;    public class Student {      @ContentAnnotation(value = "backcoder")      private String name;      @ContentAnnotation      private Integer age;        public String getName() {          return name;      }        public void setName(String name) {          this.name = name;      }        public Integer getAge() {          return age;      }        public void setAge(Integer age) {          this.age = age;      }  }  

接下來,我們寫個示常式序去獲取自定義註解裡面的內容。

package com.wpw.springboot;    import java.lang.reflect.Field;    public class MyTest2 {      public static void main(String[] args) throws NoSuchFieldException {          Class<Student> studentClass = Student.class;          Field studentClassDeclaredField = studentClass.getDeclaredField("name");          boolean flag = studentClassDeclaredField.isAnnotationPresent(ContentAnnotation.class);          if (flag){              System.out.println("屬性name是被註解進行修飾的");          }          ContentAnnotation fieldAnnotation = studentClassDeclaredField.getAnnotation(ContentAnnotation.class);          String value = fieldAnnotation.value();          System.out.println(value);          Field studentClassDeclaredField1 = studentClass.getDeclaredField("age");          ContentAnnotation field1Annotation = studentClassDeclaredField1.getAnnotation(ContentAnnotation.class);          String value1 = field1Annotation.value();          System.out.println(value1);      }  }  

首先,我們獲取自己定義類的Class對象,然後根據指定的屬性名去獲取對應的Field值,然後就根據Field去獲取屬性上面的註解,最後就可以獲取自定義註解上面的內容了,相信當你讀完這句話的時候,你已經掌握了我告訴你的內容了,壞笑。

在這裡有個很有意思的事情,每次當我寫完這段話的時候,自己總會想到另外一個人嘲諷的意思,其實寫文章幫助了自己很多,減少了很多缺點,也學會了很多技術之外的事情,其實古人的很多名言都確實很有意思,這也是自己有的時候特想說的,中文文字的魅力就在於它體現的意境,不可置否。

好了,講解上面的自定義註解的內容,我們這篇文章就到這裡結束了

Tags: