java declared_Java Class getDeclaredAnnotation()用法及代码示例
时间: 2024-03-21 07:42:35 浏览: 15
`getDeclaredAnnotation(Class<T> annotationClass)`方法可以用来获取指定注解类型的注解对象。它会从当前类的声明注解中查找,不会从父类中查找。
下面是一个简单的示例代码:
```java
import java.lang.annotation.*;
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation {
String value();
}
@MyAnnotation("Hello World")
public class MyClass {
public static void main(String[] args) {
MyAnnotation annotation = MyClass.class.getDeclaredAnnotation(MyAnnotation.class);
System.out.println(annotation.value()); // 输出:Hello World
}
}
```
在这个示例中,我们定义了一个注解 `MyAnnotation`,并将其应用在 `MyClass` 类上。然后,在 `main` 方法中使用 `getDeclaredAnnotation` 方法获取 `MyAnnotation` 类型的注解对象,并输出注解中的 `value` 值。
需要注意的是,`getDeclaredAnnotation` 方法返回的是指定注解类型的注解对象,如果当前类中没有声明该注解,则返回 `null`。此外,在使用该方法时,需要通过泛型参数指定注解类型。