其他分享
首页 > 其他分享> > 注解结合反射,天衣无缝

注解结合反射,天衣无缝

作者:互联网

请看示例代码

    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();
    }

标签:aClass,天衣无缝,String,反射,System,注解,println,import,out
来源: https://www.cnblogs.com/flyingrun/p/16513477.html