java注解简单使用
在发开过程中一直都有使用到注解,今天总算想起来研究一下注解的实现过程了。直接开车吧
// 自定义注解
// 这里已经实现了Annotation
// 注意,注解只有在反射调用的方式下才能有效
@Retention(value = RetentionPolicy.RUNTIME)
@Target(value = {ElementType.METHOD,ElementType.FIELD})
public @interface InterfaceTest {
String value();
}
我们自定义注解是依赖jdk的注解进行开发
@Retention注解是用于告诉编译器如何工作
- @Retention(value = RetentionPolicy.RUNTIME) 编译器将把注释记录在类文件中,在运行时 VM 将保留注释,因此可以反射性地读取。
SOURCE 编译器要丢弃的注释。
CLASS 编译器将把注释记录在类文件中,但在运行时 VM 不需要保留注释。这是默认的行为。
一般开发使用RUNTIME
@Target主要告诉该注解作用在哪里,可以使用多个
@Target(value = ElementType.METHOD) 作用在方法上
FIELD 字段声明(包括枚举常量)属性
TYPE 类、接口(包括注释类型)或枚举声明
ANNOTATION_TYPE 注释类型声明
CONSTRUCTOR 构造方法声明
public class TestInterfaceTest {
@InterfaceTest(value = "哈哈哈")
public static String name;
public static void main(String[] args) throws Exception {
Class<TestInterfaceTest> aClass = TestInterfaceTest.class;
Object obj = aClass.newInstance();
Method method = aClass.getMethod("test", new Class[]{int.class});
// 是否用了注解
boolean annotationPresent = method.isAnnotationPresent(InterfaceTest.class);
if (annotationPresent) {
// 获取该注解
InterfaceTest annotation = method.getAnnotation(InterfaceTest.class);
// 获取该注解上的值
String value = annotation.value();
Object invoke = method.invoke(obj, 1);
System.out.println(value + invoke);
}
Field name = aClass.getField("name");
boolean is = name.isAnnotationPresent(InterfaceTest.class);
if (is) {
InterfaceTest annotation = name.getAnnotation(InterfaceTest .class);
String value = annotation.value();
name.set(obj,value);
}
System.out.println(InterfaceTest.name);
}
@InterfaceTest(value = "注解的值")
public int test(int s) {
System.out.println("===============");
return s;
}
}