JAVA 自定义注解

4 篇文章 0 订阅
1 篇文章 0 订阅

一、创建自定义注解

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();
		}
	}
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值