设为首页 加入收藏

TOP

Java注解(Annotation)详解(三)
2015-07-20 12:52:34 来源: 作者: 【 】 浏览:37
Tags:Java 注解 Annotation 详解
个有用的工具类")
public class Utility {
? ? @Author(name="jlq",group="grape")
? ? public String work(){
? ? ? ? return "work over!";
? ? }
}


提取注解
package org.grape.annotation;


import java.lang.reflect.Method;


public class AnalysisAnnotation {
? ? public static void main(String[] args) {
? ? ? ? try {
? ? ? ? ? ? Class rt_class = Class.forName("org.grape.annotation.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类Utility.java关联的信息,即描述和作者。
运行AnalysisAnnotation,输出结果为:
Utility’s Description—>这是一个有用的工具类
Utility’s Author—>jlq from grape


首页 上一页 1 2 3 下一页 尾页 3/3/3
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇排序算法之二分法(折半)插入排.. 下一篇排序算法之三路划分的快速排序

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: