springboot java Class getAnnotation demo
时间: 2024-03-02 18:50:09 浏览: 27
好的,下面是一个简单的 Spring Boot Java 类获取注解的示例代码:
首先,创建一个自定义注解,并在需要使用的类上添加该注解:
```java
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface DemoAnnotation {
String value() default "";
}
```
然后,在需要获取注解信息的类中,使用 `getAnnotation` 方法获取注解对象,并调用注解中的属性:
```java
@DemoAnnotation(value = "demo")
public class DemoClass {
public static void main(String[] args) {
Class<?> clazz = DemoClass.class;
DemoAnnotation annotation = clazz.getAnnotation(DemoAnnotation.class);
if (annotation != null) {
System.out.println(annotation.value());
}
}
}
```
以上代码会输出 `demo`。
需要注意的是,为了使注解信息在运行时可见,需要在注解定义中添加 `@Retention(RetentionPolicy.RUNTIME)` 注解。并且,使用 `getAnnotation` 方法获取的注解对象可能为空,因此需要进行非空判断。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)