用 java 实现取指定注解的值

在Java中,你可以利用反射API来获取类或方法上的注解,并从中读取特定的值。这里是一个简单的例子,展示如何实现这一功能:

首先,假设你有一个自定义注解:

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.METHOD)
public @interface MyAnnotation {
    String value();
}

接下来,在某个类的方法上使用这个注解:

public class ExampleClass {
    @MyAnnotation(value = "Hello, world!")
    public void annotatedMethod() {
        // 方法体
    }
}

现在,如果你想从ExampleClassannotatedMethod方法中获取MyAnnotation注解的值,你可以这样做:

import java.lang.reflect.Method;

public class AnnotationReader {
    public static void main(String[] args) {
        Class<ExampleClass> clazz = ExampleClass.class;
        try {
            Method method = clazz.getMethod("annotatedMethod");
            MyAnnotation annotation = method.getAnnotation(MyAnnotation.class);
            if (annotation != null) {
                System.out.println("注解值:" + annotation.value());
            } else {
                System.out.println("没有找到注解");
            }
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
    }
}

这段代码首先通过反射获取到了ExampleClass类中的annotatedMethod方法,然后调用了getAnnotation方法来获取该方法上的MyAnnotation注解。如果该方法上有此注解,则打印出注解的value属性值。

这个例子展示了如何从方法上获取注解,同样的方法也可以应用于类、字段、构造器等其他程序元素上。如果你需要从类级别的注解获取值,只需将getMethod改为getDeclaredAnnotation即可。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值