注解结合反射,天衣无缝


请看示例代码

    package com.xxd.modules.util;
    
    import lombok.AllArgsConstructor;
    import lombok.Data;
    import lombok.NoArgsConstructor;
    import lombok.ToString;
    
    import java.lang.annotation.*;
    import java.lang.reflect.Field;
    import java.lang.reflect.InvocationTargetException;
    import java.lang.reflect.Method;
    
    public class RefTest {
    
        public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException {
            Class aClass = Class.forName("com.xxd.modules.util.Student");
            Student student = (Student) aClass.newInstance();
            // 通过反射执行方法
            Method method = aClass.getDeclaredMethod("setName", String.class);
            method.invoke(student, "润哥");
            System.out.println(student);
    
            // 通过反射获取注解
            Annotation[] annotations = aClass.getAnnotations();
            for (Annotation annotation : annotations) {
                System.out.println(annotation);
            }
    
            // 获取指定注解的值
            TableRun tableRun = (TableRun) aClass.getAnnotation(TableRun.class);
            String value = tableRun.value();
            System.out.println(value);
    
            // 获取属性中指定的注解
            Field field = aClass.getDeclaredField("name");
            FieldRun fieldRun = field.getAnnotation(FieldRun.class);
            System.out.println(fieldRun.columnName());
            System.out.println(fieldRun.type());
            System.out.println(fieldRun.length());
    
        }
    }
    
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    @ToString
    @TableRun("db_student")
    class Student {
        @FieldRun(columnName = "id", type = "int", length = 8)
        private int id;
        @FieldRun(columnName = "age", type = "int", length = 8)
        private int age;
        @FieldRun(columnName = "name", type = "varchar", length = 8)
        private String name;
    
    }
    
    // 类名的注解
    @Target(ElementType.TYPE)
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    @interface TableRun {
        String value();
    }
    
    // 属性的注解
    @Retention(RetentionPolicy.RUNTIME)
    @Target(ElementType.FIELD)
    @Documented
    @interface FieldRun {
        String columnName();
    
        String type();
    
        int length();
    }

原创文章,作者:kirin,如若转载,请注明出处:https://blog.ytso.com/tech/pnotes/276536.html

(0)
上一篇 2022年7月24日 00:30
下一篇 2022年7月24日 00:49

相关推荐

发表回复

登录后才能评论