注解测试类

package demo.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;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Documented
public @interface Author {
String name();
String group();
}

package demo.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;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
public @interface Description {
String value();
}

package demo.annotation;

import java.lang.reflect.Method;

@Description(value="这是一个有用的工具类")
public class Utility {

@Author(name="haoran_202",group="com.magc")
public String work(){
return "work over";
}
public static void main(String[] args) {
try {
Class rt_class=Class.forName("demo.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("description value:"+description.value());
for(Method method:methods){
if(method.isAnnotationPresent(Author.class)){
Author author=(Author)method.getAnnotation(Author.class);
System.out.println("author name:"+author.name()+",group:"+author.group());
}
}
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

posted @ 2015-12-31 09:45  java高级技术汇  阅读(438)  评论(0编辑  收藏  举报