java注解简单使用

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;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值