The basic method of reflection to get attribute method annotations

When the program is running, we need to get some information about the class, we can use reflection to get it

1. Preparation

First, you need a class and an annotation, the annotation is on this class

/**
 * 用于练习反射的类
 *
 * @author dongzhiwei
 * @date 2020/9/21 16:55
 */
@MyAnno(id = 12,userCode = "AB123")
public class ReflectBean {
    
    

    /**
     * 名称
     */
    private String name;

    /**
     * 身份证
     */
    public String idCode;
    
    /**
     * 名称
     */
    private String name;

    /**
     * 身份证
     */
    public String idCode;


    public String getName() {
    
    
        return name;
    }

    public void setName(String name) {
    
    
        this.name = name;
    }

    public String getIdCode() {
    
    
        return idCode;
    }

    public void setIdCode(String idCode) {
    
    
        this.idCode = idCode;
    }

	public int invokeTest(String userCode, Integer age) {
    
    

        int total = 10;
        total = total + age;
        System.out.println("用户code:"+userCode+"总数为:"+total);
        return total;
    }
}
/**
 * @author dongzhiwei
 */
@Target({
    
    ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnno {
    
    
    int id();
    String userCode();
}

2. Obtained by reflection

2.1 First get the class object

// 通过类路径来获取(较常用)
1. Class<?> aClass = Class.forName("com.example.demo.model.ReflectBean");
// 直接通过类.class 获取
2. Class<ReflectBean> reflectBeanClass = ReflectBean.class;
// 通过实例来获取
3. ReflectBean reflectBean = new ReflectBean();
   Class<? extends ReflectBean> aClass1 = reflectBean.getClass();

2.2 Get the attribute value of the class

    @Test
    void getFields() throws  IllegalAccessException {
    
    
        ReflectBean reflectBean = new ReflectBean();
        Class<? extends ReflectBean> aClass = reflectBean.getClass();
        Field[] fields = aClass.getDeclaredFields();
        for (Field field : fields) {
    
    
            System.out.println(field);
            //设置暴力访问 破坏封装,可以调用私有成员
            field.setAccessible(true);
            // 设置字段值
            field.set(reflectBean,"name");
        }
    }

2.3 Methods of obtaining classes

@Test
    void getMethod() throws ClassNotFoundException, IllegalAccessException, InstantiationException, InvocationTargetException {
    
    
        Class<?> aClass = Class.forName("com.example.demo.model.ReflectBean");
        //获取实例对象
        Object o = aClass.newInstance();
        Method[] methods = aClass.getMethods();
        for (Method method : methods) {
    
    
            System.out.println("修饰符: " + method.getModifiers());
            System.out.println("返回值: " + method.getReturnType());
            System.out.println("方法名称: " + method.getName());
            System.out.println("参数列表: " + method.getParameterTypes());
            if (method.getName().equals("invokeTest")) {
    
    
                // 反射调用方法  第一个参数是对象的实例 后面是方法的参数
                Object code = method.invoke(o, "code", 10);
                System.out.println("调用addResult后的运行结果:" + code);
            }
        }
    }

operation result
Insert picture description here

2.4 Get the annotations on the class

    @Test
    void getAnno() throws ClassNotFoundException {
    
    
        Class<?> aClass = Class.forName("com.example.demo.model.ReflectBean");
        MyAnno annotation = aClass.getAnnotation(MyAnno.class);
        Map<String, Object> attributes = AnnotationUtils.getAnnotationAttributes(annotation);
        Object userCode = attributes.get("userCode");
        System.out.println(userCode);
        System.out.println(annotation.id());
        System.out.println(annotation.userCode());
    }

result
Insert picture description here

Guess you like

Origin blog.csdn.net/hgdzw/article/details/108715500