java反射获取注解的值
时间: 2023-10-05 20:10:17 浏览: 59
可以使用Java反射中的getAnnotation方法获取注解的值。具体可以参考以下代码:
```java
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Method;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation {
String value();
}
public class ReflectionDemo {
@MyAnnotation("Hello, World!")
public void myMethod() {
// do something
}
public static void main(String[] args) throws Exception {
ReflectionDemo demo = new ReflectionDemo();
Method method = demo.getClass().getMethod("myMethod");
MyAnnotation annotation = method.getAnnotation(MyAnnotation.class);
System.out.println(annotation.value()); // 输出 "Hello, World!"
}
}
```
以上代码定义了一个名为`MyAnnotation`的注解,并在`ReflectionDemo`类的`myMethod`方法上使用了该注解。在`main`方法中,通过反射获取了`myMethod`方法,并使用`getAnnotation`方法获取了该方法上的`MyAnnotation`注解,并最后将注解的值输出。