package com.dhgate.prod.impl;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.TYPE,ElementType.METHOD,ElementType.CONSTRUCTOR,ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface ATest {
String name();
int id() default 0;
Class<Long> gid() default Long.class;
}
package com.dhgate.prod.impl;
@ATest(name="type",gid=Long.class)
public class ATT {
@ATest(name="param",id=1)
private int age;
@ATest(name="constructor",id=2)
public ATT() {
// TODO Auto-generated constructor stub
}
@ATest(name="public method",id=3)
public void print(){
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@ATest(name="print method",id=4)
public void print(String msg){
System.out.println("msg: "+msg);
}
}
package com.dhgate.prod.impl;
import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
public class BParseAnotation {
public static void parseTypeAnotation() throws ClassNotFoundException{
Class clazz = Class.forName("com.dhgate.prod.impl.ATT");
Annotation[] annotations = clazz.getAnnotations();
for(Annotation annotation:annotations){
ATest testA = (ATest) annotation;
System.out.println("id= \""+testA.id()+"\";name=\""+testA.name()+"\";gid="+testA.gid());
}
}
public static void parseMethodAnnotation(){
Method[] methods = ATT.class.getDeclaredMethods();
for(Method m:methods){
boolean hasAnnotation = m.isAnnotationPresent(ATest.class);
if(hasAnnotation){
ATest annotation = m.getAnnotation(ATest.class);
System.out.println("method="+m.getName()+" id="+annotation.id()+" description"+annotation.name()+" gid="+annotation.gid());
}
}
}
public static void parseConstructAnnotation(){
Constructor[] constructor = ATT.class.getConstructors();
for(Constructor con:constructor){
boolean hasConstructor = con.isAnnotationPresent(ATest.class);
if(hasConstructor){
ATest annotation = (ATest) con.getAnnotation(ATest.class);
System.out.println("constructor="+con.getName()+" id:"+annotation.id()+
" description:"+annotation.name()+" gid="+annotation.gid());
}
}
}
public static void main(String[] args) throws ClassNotFoundException {
parseConstructAnnotation();
parseMethodAnnotation();
parseTypeAnotation();
}
}