java 类,变量,方法上注解值的获取

首先定义三个注解类, 分别适用于类,成员变量, 方法

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface LeiMode {
	public int value() default 1;
}

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface FiledMode {
	public int value() default 1;
}

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface TreahMode {
	public int value() default 1;
}

然后,定义一个类,使用了注解

@LeiMode(5)
public class AnnotationDemo {
	
	@FiledMode(10)
	private int itest;
	
	@TreahMode()
	private void test(){}
}


1.获取类上的注解值

LeiMode annotation = AnnotationDemo.class.getAnnotation(LeiMode.class);
System.out.println(annotation.value());


2.获取所有变量,并获取指定方法上的注解信息

Field[] fields = AnnotationDemo.class.getDeclaredFields();
		Field field = null;
		for(Field f : fields){
			if(f.getName().equals("itest")){
				field = f;
				break;
			}
		}
		
		FiledMode annotation = field.getAnnotation(FiledMode.class);
		System.out.println(annotation.value());


3.获取指定变量上的注解信息

Field field = AnnotationDemo.class.getDeclaredField("itest");
		FiledMode annotation = field.getAnnotation(FiledMode.class);
		
		System.out.println(annotation.value());

4.获取所有方法,并获取指定方法上的注解信息

Method[] methods = AnnotationDemo.class.getDeclaredMethods(); //可以获取私有方法和公有方法, getMethods() 获取公有方法
		Method meth = null;
		for(Method method : methods){
			if(method.getName().equals("test")){
				meth = method;
				break;
			}
		}
		Annotation annotation = meth.getAnnotations()[0];
		TreahMode mode = (TreahMode) annotation;
		System.out.println(mode.value());

5.获取指定方法上的注解信息

Method method = AnnotationDemo.class.getDeclaredMethod("test", null);//可以获取私有方法和公有方法
		System.out.println(method);
		Annotation[] annotations = method.getAnnotations();
		Annotation annotation = annotations[0];
		System.out.println(annotation);
		
		TreahMode mode = (TreahMode) annotation;
		System.out.println(mode.value());






评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值