package com.james.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;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Description {
String value();
}
是定义对类的注解
package com.james.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;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Name {
String originage();
String community();
}
是定义对方法的注解
package com.james.annotation;
@Description(value="This is James' community!")
public class Mycommunity {
@Name(originage="james",community="DP")
public String getName(){
return null;
}
@Name(originage="cindy",community="TX")
public String getName2(){
return null;
}
}
将注解应用于类和方法
package com.james.annotation;
import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.Set;
public class TestAnnotation {
/**
* @param args
*/
public static void main(String[] args) throws Exception{
String className = "com.james.annotation.Mycommunity";
Class cla = Class.forName(className);
Method[] methods = cla.getMethods();
boolean flag = cla.isAnnotationPresent(Description.class);
if(flag){
Description des = (Description)cla.getAnnotation(Description.class);
System.out.println("描述:"+des.value());
System.out.println("-------------------");
}
Set<Method> set = new HashSet<Method>();
for(int i=0;i<methods.length;i++){
boolean methodFlag = methods[i].isAnnotationPresent(Name.class);
if(methodFlag) set.add(methods[i]);
}
for (Method m:set){
Name name = m.getAnnotation(Name.class);
System.out.println("Org: "+name.originage());
System.out.println("Comm: "+name.community());
}
}
}
分别获取类和方法的注解信息!