package annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
//RUNTIME表示运行时Person注解也存在
//@Retention(RetentionPolicy.CLASS)
@Retention(RetentionPolicy.RUNTIME)
@interface Person {
String name();
int age();
}
@Person(name="Tom",age=20)
class Test1{}
@Person(name="Jack",age=22)
class Test2{}
//@Person(name="Anna",age=18)
class Test3{}
public class AnnotationTest{
public static void printClassInto(Class c){
System.out.print(c.getName()+". ");
Person person = (Person) c.getAnnotation(Person.class);
if (person!=null) {
System.out.println("Person: "+person.name()+" ,age:"+person.age());
}
else {
System.out.println("unknown person");
}
}
public static void main(String[] args) {
printClassInto(Test1.class);
printClassInto(Test2.class);
printClassInto(Test3.class);
}
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文:http://blog.csdn.net/wanghao109/article/details/46851849