个有用的工具类")
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