Java 自定義注解及利用反射讀取注解


一、自定義注解

元注解: 

@interface注解: 定義注解接口

@Target注解: 用於約束被描述的注解的使用范圍,當被描述的注解超出使用范圍則編譯失敗。如:ElementType.METHOD,ElementType.TYPE;

@Retention 注解:用於約束被定義注解的作用范圍,作用范圍有三個:

1,、RetentionPolicy.SOURCE:作用范圍是源碼,作用於Java文件中,當執行javac時去除該注解。

2、RetentionPolicy.CLASS:作用范圍是二進制碼,就是存在於class文件中,當執行Java時去除該注解。

3、RetentionPolicy.RUNTIME:作用范圍為運行時,就是我們可以通過動態獲取該注釋。

@Documented:用於指定javadoc生成API文檔時顯示該注釋。

@Inherited:用於指定被描述的注釋可以被其描述的類的子類繼承,默認情況是不能被其子類繼承。

自定義注解接口:

 

 1 package com.java.annotation;
 2 
 3 import java.lang.annotation.Documented;
 4 import java.lang.annotation.ElementType;
 5 import java.lang.annotation.Inherited;
 6 import java.lang.annotation.Retention;
 7 import java.lang.annotation.RetentionPolicy;
 8 import java.lang.annotation.Target;
 9 
10 @Target({ElementType.METHOD,ElementType.TYPE})
11 @Inherited
12 @Documented
13 @Retention(RetentionPolicy.RUNTIME)
14 public @interface Annotation_my {
15     
16     String name() default "張三";//defalt 表示默認值
17     
18     String say() default "hello world";
19     
20     int age() default 21;
21     
22 }

 

接下來我們定義一個接口:

package com.java.annotation;

@Annotation_my //使用我們剛才定義的注解
public interface Person {
    
    @Annotation_my
    public void name();
    
    @Annotation_my
    public void say();
    
    @Annotation_my
    public void age();

}

接口定義好了,我們就可以寫接口的實現類了(接口不能實例化)

package com.java.annotation;

@Annotation_my
@SuppressWarnings("unused")
public class Student implements Person {
    
    private String name;

    @Override
    @Annotation_my(name="流氓公子") //賦值給name  默認的為張三
//在定義注解時沒有給定默認值時,在此處必須name賦初值
    public void name() {
        
    }


    @Override
    @Annotation_my(say=" hello world  !")
    public void say() {
        
    }

    @Override
    @Annotation_my(age=20)
    public void age() {
        
    }
}

然后我們就編寫一個測試類測試我們的注解

package com.java.annotation;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class Text {
    Annotation[] annotation = null;

    public static void main(String[] args) throws ClassNotFoundException {
        new Text().getAnnotation();
    }
    
    public void getAnnotation() throws ClassNotFoundException{
        Class<?> stu = Class.forName("com.java.annotation.Student");//靜態加載類
        boolean isEmpty = stu.isAnnotationPresent(com.java.annotation.Annotation_my.class);//判斷stu是不是使用了我們剛才定義的注解接口if(isEmpty){
            annotation = stu.getAnnotations();//獲取注解接口中的
            for(Annotation a:annotation){
                Annotation_my my = (Annotation_my)a;//強制轉換成Annotation_my類型
                System.out.println(stu+":\n"+my.name()+" say: "+my.say()+" my age: "+my.age());
            }
        }
        Method[] method = stu.getMethods();//
        System.out.println("Method");
        for(Method m:method){
            boolean ismEmpty = m.isAnnotationPresent(com.java.annotation.Annotation_my.class);
            if(ismEmpty){
                Annotation[] aa = m.getAnnotations();
                for(Annotation a:aa){
                    Annotation_my an = (Annotation_my)a;
                    System.out.println(m+":\n"+an.name()+" say: "+an.say()+" my age: "+an.age());
                }
            }
        }
        //get Fields by force
        System.out.println("get Fileds by force !");
        Field[] field = stu.getDeclaredFields();
        for(Field f:field){
            f.setAccessible(true);
            System.out.println(f.getName());
        }
        System.out.println("get methods in interfaces !");
        Class<?> interfaces[] = stu.getInterfaces();
        for(Class<?> c:interfaces){
            Method[] imethod = c.getMethods();
            for(Method m:imethod){
                System.out.println(m.getName());
            }
        }
    }

}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM