码迷,mamicode.com
首页 > 编程语言 > 详细

java annotation

时间:2016-07-04 18:46:11      阅读:147      评论:0      收藏:0      [点我收藏+]

标签:

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();
            }
    }

}

 

java annotation

标签:

原文地址:http://www.cnblogs.com/sprinng/p/5641104.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!