自定義Java annotation及解析和使用

用@interface定義一個annotation:

package annotationTest;

import java.lang.annotation.*;

@Documented
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MethodInfo {
    String author() default "Jerry";
    String version() default "1.0";
    String date();
    String comment();
}


新建一個類,給其方法添加上剛纔創建的註解:

package annotationTest;

// Jerry change for demo

public class AnnotationExample {
    @Override
    @MethodInfo(author = "xxx",version = "1.0",date = "2015/03/26",comment = "override toString()")
    public String toString() {
        return "AnnotationExample{}";
    }

    @Deprecated
    @MethodInfo(comment = "deprecated method", date = "2015/03/26")
    public static void oldMethod() {
        System.out.println("old method, don't use it.");
    }

    @MethodInfo(author = "Pankaj", comment = "Main method", date = "Nov 17 2012", version = "1.0")
    public static void genericsTest() {
        oldMethod();
    }
}

打印的輸出:

@annotationTest.MethodInfo(version="1.0", author="xxx", date="2015/03/26", comment="override toString()") in method:public java.lang.String annotationTest.AnnotationExample.toString()


Method with revision no 1.0 = public java.lang.String annotationTest.AnnotationExample.toString()
@annotationTest.MethodInfo(version="1.0", author="Pankaj", comment="Main method", date="Nov 17 2012") in method:public static void annotationTest.AnnotationExample.genericsTest()


Method with revision no 1.0 = public static void annotationTest.AnnotationExample.genericsTest()
@java.lang.Deprecated(forRemoval=false, since="") in method:public static void annotationTest.AnnotationExample.oldMethod()
@annotationTest.MethodInfo(version="1.0", author="Jerry", comment="deprecated method", date="2015/03/26") in method:public static void annotationTest.AnnotationExample.oldMethod()


Method with revision no 1.0 = public static void annotationTest.AnnotationExample.oldMethod()

同理,新建一個description註解,用來修飾People類:

package annotationTest;

import java.lang.annotation.Documented;
import java.lang.annotation.Inherited;
import java.lang.annotation.*;

@Target({ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface Description {
	 String desc();
	 String author();
	 int age() default 18;
}
package annotationTest;

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

@Description(author = "Jerry", desc = "Class annotation", age = 35)
public class People {
	
	@Description(author = "Jerry 2", desc = "method annotation", age = 35)
	public void hello(){
		
	}
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static void main(String[] arg){
	        try {
	            // 使用類加載器加載類
	            Class c = Class.forName("annotationTest.People");
	            // 找到類上面的註解
	            boolean isExist = c.isAnnotationPresent(Description.class);
	            // 上面的這個方法是用這個類來判斷這個類是否存在Description這樣的一個註解
	            if (isExist) {
	                // 拿到註解實例,解析類上面的註解
	                
	            	Description d = (Description) c.getAnnotation(Description.class);
	                System.out.println(d.desc());
	            }
	            
	          //獲取所有的方法
	            Method[] ms = c.getMethods();
	            // 遍歷所有的方法
	            for (Method m : ms) {
	                boolean isExist1 = m.isAnnotationPresent(Description.class);
	                if (isExist1) {
	                    Description d1=m.getAnnotation(Description.class);
	                    System.out.println(d1.desc());
	                }
	            }
	            
	          //另一種解析方法
	            for (Method m : ms) {
	                //拿到方法上的所有的註解
	                Annotation[] as=m.getAnnotations();
	                for (Annotation a : as) {
	                    //用二元操作符判斷a是否是Description的實例
	                    if (a instanceof Description) {
	                        Description d=(Description) a;
	                        System.out.println(d.desc());
	                    }
	                }
	            }
	            
	            
	        } catch (ClassNotFoundException e) {
	            e.printStackTrace();
	        }
	    }
	}

輸出:

Class annotation
method annotation
method annotation

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章