Java注解之运行时注解

注解的生命周期

  • RetentionPolicy.SOURCE 注解只在源代码中,编译成class文件之后,就没了
  • RetentionPolicy.CLASS 注解在java文件编译成class文件之后,依然存在,但是运行起来就没有了
  • RetentionPolicy.RUNTIME 注解在运行起来之后依然存在,程序可以通过类反射获取这些信息

RetentionPolicy.RUNTIME

这里我们介绍运行时注解

  1. 首先建立一个自定义注解

@Retention(RetentionPolicy.RUNTIME)
public @Interface FaceDemo{
		String value() default "";
}
  1. 使用自定义注解
public class FaceTest {
		@FaceDemo
		public String str ="";
}
  1. 创建一个解析器
public class FaceDemoProcessor {
		public static void main(String[] args){
				Class<?> cls = FaceTest.class;
				try{
						Field str = cls.getField("str");//获取指定成员属性
						boolean b = str.isAnnotationPresent(FaceDemo.class);//这个属性上是否有这个注解
						if(b){
						  //获取所有的注解
						  Annotation[] annotations = str.getAnnotations();
						  System.out.println(annotations.length);
						  //获取指定注解
						  FaceDemo annotation = str.getAnnotation(FaceDemo.class);
						  System.out.println(annotation.value());
					   }
				} catch (NoSuchFieldException e) {
				  e.printStackTrace();
				}
		}
}
  1. 输出
1
自定义运行时注解
  1. 通过类反射获取注解的几个常用方法
/**
 * 获取指定类型的注解
 */
public <A extends Annotation> A getAnnotation(Class<A> annotationType);
 
/**
 * 获取所有注解
 */
public Annotation[] getAnnotations();
 
/**
 * 获取所有注解,忽略继承的注解
 */
public Annotation[] getDeclaredAnnotations();
 
/**
 * 指定注解是否存在该元素上,如果有则返回true,否则false
 */
public boolean isAnnotationPresent(Class<? extends Annotation> annotationType);
 
/**
 * 获取Method中参数的所有注解
 */
public Annotation[][] getParameterAnnotations();

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值