Java开发 自定义注解(更新中)
问题:若设置了一个自定义注解,如何获取自定义注解的值
1.建立一个自定义注解类 MyAnnotation
package com.test.springboot_test.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;@Target({ElementType.FIELD, ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {/*** 在这个例子中: @Target注解指定了MyAnnotation可以应用的目标,* 这里可以应用于方法(ElementType.METHOD)和类(ElementType.TYPE)* 类的字段上ElementType.FIELD 表示注解可以应用于类的字段(属性)上。。* @Retention注解指定了注解的保留策略,这里是RetentionPolicy.RUNTIME,* 意味着注解在运行时也可以被获取到。 定义了一个名为value的元素,它是一个字符串类型,并且有一个默认值为空字符串。* @return*/String value() default "";
}
2.在实体类上面使用该注解
package com.test.springboot_test.domain;import com.baomidou.mybatisplus.annotation.*;
import com.test.springboot_test.annotation.MyAnnotation;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;@Data
@AllArgsConstructor
@NoArgsConstructor
@TableName("employee")
public class Employee {//姓名@NotNull@MyAnnotation("这是一个自定义注解的测试")private String name;
}
3.我们在测试类上面获取自定义注解的值
/*** 2025-5-6* 如何通过反射获取自定义注解定义的值*/@Testvoid testAnnotation() throws NoSuchFieldException {Class<Employee> employeeClass = Employee.class;Field field = employeeClass.getDeclaredField("name");MyAnnotation annotation = field.getAnnotation(MyAnnotation.class);System.out.println(annotation);System.out.println(field.getName());//获取字段名System.out.println(field.getType());//获取字段的类型System.out.println(field.getAnnotation(MyAnnotation.class));System.out.println(annotation.value());//获取自定义注解的内容}