多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
自定义注解的步骤如下: **1. 定义注解** ```java /** * 1. 注解使用@interface来声明 * 2. 修饰符只能是public * 3. 自定义注解会自动继承java.lang.annotation.Annotaion接口 */ //定义该注解只有在运行时起作用 @Retention(RetentionPolicy.RUNTIME) //定义该注解可以用在类、接口、枚举、属性、方法上 @Target({ElementType.TYPE, ElementType.FIELD, ElementType.METHOD}) public @interface CustomAnnotation { /** * 注解的属性规则 * 1. 注解只有属性,没有方法 * 2. 属性的类型可以是:8种基本数据类型、String、类、接口、注解、以及它们对应的数组 * 3. 属性可以通过default关键字来设定默认值 * 4. 如果你的注解只有一个属性,请用value关键字来命名 */ String value() default ""; //虽然value()看似方法,但请注意它是一个属性 String description() default ""; // 提供默认值 int[] num() default 0; String elementType() default ""; } ``` **2. 应用注解** ```java @CustomAnnotation(description = "狗对象", elementType = "现在是用在类上", num = {1, 2}) public class Dog { @CustomAnnotation(description = "狗的属性-品种", elementType = "现在是用在属性上") private String verity; @CustomAnnotation(description = "狗的属性-性别", elementType = "现在是用在属性上") private String sex; @CustomAnnotation(description = "狗的行为", elementType = "现在是用在方法上") public void eat() { System.out.println("狗喜欢吃骨头!"); } } ``` **3. 根据反射获取注解** ```java @Test public void test() throws ClassNotFoundException, NoSuchMethodException, SecurityException { //反射Dog类 Class<Dog> cls = (Class<Dog>) Class.forName("com.learn.annotation01.model.Dog"); //判断该类是否使用注解CustomAnnotation if (cls.isAnnotationPresent(CustomAnnotation.class)) { //获取Dog类上的注解 CustomAnnotation customAnnotation = cls.getAnnotation(CustomAnnotation.class); System.out.println("description: " + customAnnotation.description() + ", elementType: " + customAnnotation.elementType()); //description: 狗对象, elementType: 现在是用在类上 } //获取Dog类的所有属性 Field[] fields = cls.getDeclaredFields(); for (Field field : fields) { //判断当前属性是否使用注解CustomAnnotation if (field.isAnnotationPresent(CustomAnnotation.class)) { //获取当前属性上的注解 CustomAnnotation customAnnotation = field.getAnnotation(CustomAnnotation.class); System.out.println("description: " + customAnnotation.description() + ", elementType: " + customAnnotation.elementType()); //description: 狗的属性-品种, elementType: 现在是用在属性上 //description: 狗的属性-性别, elementType: 现在是用在属性上 } } //获取Dog类的eat方法 Method eatMethod = cls.getDeclaredMethod("eat"); //判断当前方法是否使用了注解 if (eatMethod.isAnnotationPresent(CustomAnnotation.class)) { CustomAnnotation customAnnotation = eatMethod.getAnnotation(CustomAnnotation.class); System.out.println("description: " + customAnnotation.description() + ", elementType: " + customAnnotation.elementType()); //description: 狗的行为, elementType: 现在是用在方法上 } } ```