一、创建自定义注解
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.ANNOTATION_TYPE,ElementType.METHOD,ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface XJPath{
String name() default "XJ";
int age() default 2;
}
说明:
@Target,@Retention,@Inherited,@Documented为元注解(meta-annotation),他们是负责注解其它注解的。
1.Target:指明注解的使用范围,取值可以参考枚举ElementType,一下:
ElementType.TYPE //类,接口,枚举
ElementType.FIELD // 属性
ElementType.METHOD //方法
ElementType.PARAMETER //参数
ElementType.CONSTRUCTOR //构造器
ElementType.LOCAL_VARIBLE //局部变量
ElementType.ANNOTATION_TYPE //注解
ElementType.PACKAGE //包
2.Retention: 指明注解保留的时间长短,取值参考RetentionPolicy,以下:
SOURCE // 源文件中保留
CLASS //class编译时保留
RUNTIME //运行时保留
3.Inherited: 指明该注解类型被自动继承,如果一个annotion注解被@Inherited修饰,那么该注解作用于的类的子类也会使用
该annotion注解。
4.Documented: 指明拥有这个注解的元素可以被javadoc 此类的工具文档化。
二,创建注解测试类
public class TestXJPath {
@XJPath(age=18)
private static int a;
@XJPath(name="xiandjin")
public void updateName(){
System.err.println("test");
}
}
在该类中的属性和方法,使用了自定义的注解,并指明了参数。
那么现在就需要解析自定义的注解
三,解析注解
使用反射的机制处理自定义注解
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class XJProcesses {
public static void main(String[] args){
try {
Class clazz = XJProcesses.class.getClassLoader().loadClass("com.hz.hzdjr.controller.TestXJPath");
Field[] field = clazz.getDeclaredFields();
for(Field f:field){
XJPath tx = f.getAnnotation(XJPath.class);
System.err.println("name:"+tx.name());
}
Method[] method = clazz.getDeclaredMethods();
for(Method m:method){
if(m.isAnnotationPresent(XJPath.class)){
XJPath an = m.getAnnotation(XJPath.class);
System.err.println(an.name());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}