清单3:Utility.java
package com.magc.annotation;
@Description(value = "这是一个有用的工具类")
@Description(value = "这是一个有用的工具类")
public class Utility {
@Author(name = "haoran_202",group="com.magc")
public String work()
@Author(name = "haoran_202",group="com.magc")
public String work()
{
return "work over!";
}
}
return "work over!";
}
}
注:这是个普通的Java类,运行了@Description和@Author注解。
清单3:AnalysisAnnotation.java
package com.magc.annotation;
import java.lang.reflect.Method;
public class AnalysisAnnotation {
/**
* 在运行时分析处理annotation类型的信息
*
*
*/
public static void main(String[] args) {
try {
//通过运行时反射API获得annotation信息
Class rt_class = Class.forName("com.magc.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());
}
}
}
}
import java.lang.reflect.Method;
public class AnalysisAnnotation {
/**
* 在运行时分析处理annotation类型的信息
*
*
*/
public static void main(String[] args) {
try {
//通过运行时反射API获得annotation信息
Class rt_class = Class.forName("com.magc.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();
}
}
}
e.printStackTrace();
}
}
}
注:这是个与自定义@Description和@Author配套的基础框架或工具类,通过此类来获得与普通Java类Utility.java关联的信息,即描述和作者。
运行AnalysisAnnotation,输出结果为:
Utility's Description--->这是一个有用的工具类
Utility's Author--->haoran_202 from com.magc
Utility's Author--->haoran_202 from com.magc