可以把注解理解为代码里的特殊标记,这些标记可以在编译,类加载,运行时被读取,并执行相应的处理。
在自定义注解类之前要知道注解类的定义方式,需要给注解类进行至少以下两个注解,没错你没听错奶奶滴,就是要给注解进行注解
@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD)@Rentention Rentention @Rentention Rentention用来标记自定义注解的有效范围,他的取值有以下三种:
RetentionPolicy.SOURCE: 只在源代码中保留 一般都是用来增加代码的理解性或者帮助代码检查之类的,比如我们的Override;RetentionPolicy.CLASS: 默认的选择,能把注解保留到编译后的字节码class文件中,仅仅到字节码文件中,运行时是无法得到的;RetentionPolicy.RUNTIME: ,注解不仅 能保留到class字节码文件中,还能在运行通过反射获取到,这也是我们最常用的。@Target @Target指定Annotation用于修饰哪些程序元素。 @Target也包含一个名为”value“的成员变量,该value成员变量类型为ElementType[ ],ElementType为枚举类型,值有如下几个:
ElementType.TYPE:能修饰类、接口或枚举类型ElementType.FIELD:能修饰成员变量ElementType.METHOD:能修饰方法ElementType.PARAMETER:能修饰参数ElementType.CONSTRUCTOR:能修饰构造器ElementType.LOCAL_VARIABLE:能修饰局部变量ElementType.ANNOTATION_TYPE:能修饰注解ElementType.PACKAGE:能修饰包以下为注解类写法
import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface BindString { String value() default ""; }被注解的类
public class AnnotationEntity { @BindString("哈哈") private String test; public void printInfo(){ System.out.println(test); } }反射获取注解并赋值给参数
Class clzz = Class.forName("com.test.application.javatest.AnnotationEntity"); //拿到构造方法 Constructor constructor = clzz.getConstructor(); //获取对象 AnnotationEntity entity = (AnnotationEntity) constructor.newInstance(); //获取注解类 //将注解内容设置给参数 Field field = clzz.getDeclaredField("test"); field.setAccessible(true); BindString testAnnotation = (BindString) field.getAnnotation(BindString.class); field.set(entity,testAnnotation.value()); //调用 entity.printInfo();