java annotation

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

    /**
     * 定义作者信息,name和group
     * @author sprinng
     *
     */
    @Retention(RetentionPolicy.RUNTIME)
    @Target(ElementType.METHOD)
    @Documented
public @interface Author {

        String name();
        String group();
}
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * @author sprinng
 *
 * 定义描述信息 value
 */
    @Retention(RetentionPolicy.RUNTIME)
    @Target(ElementType.TYPE)
    @Documented
    
public @interface Description {
        String value();
}
@Description(value = "这是一个有用的工具类")
public class Utility {

    @Author(name = "haoran_202",group="com.magc")
    public String work()
    {
        return "work over!";
    }
    
    

}
import java.lang.reflect.Method;

public class AnalysisAnnotation {

    /**
     * 在运行时分析处理annotation类型的信息
     */
    public static void main(String[] args) {
        try {
                //通过运行时反射API获得annotation信息
                Class<?> rt_class = Class.forName("com.demo.Utility");
                Method[] methods = rt_class.getMethods();
                
                boolean flag = rt_class.isAnnotationPresent(Description.class);
                
                if(flag)
                {
                    Description description = (Description)rt_class.getAnnotation(Description.class);
                    System.out.println("Utility's Description--->"+description.value());
                    for (Method method : methods) {
                        if(method.isAnnotationPresent(Author.class))
                        {
                            Author author = (Author)method.getAnnotation(Author.class);
                            System.out.println("Utility's Author--->"+author.name()+" from "+author.group());
                            
                        }
                    }
                }
            
            
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
    }

}

 

posted @ 2016-07-04 17:18  Earic  阅读(245)  评论(0编辑  收藏  举报