Reflection & AOP: Get variable name and variable value

Reflection: get variable name and variable value

Case:

public class Test{
    
    
    private static Map<String, String> fieldMap = new HashMap<>();
 
    /**
     * 发布A
     */
    public static final String PUBLISH_A= "";
    /**
     * 新建A
     */
    public static final String CREATE_A= "";
 
    static {
    
    
        Field[] fields = Test.class.getDeclaredFields();
        fieldMap = new HashMap<>();
        for(Field field : fields) {
    
    
            try {
    
    
                fieldMap.put(field.getName(), field.get(Test.class).toString());
            } catch (IllegalAccessException e) {
    
    
                e.printStackTrace();
            }
        }
    }
 
    public static String findCode(String code) {
    
    
        return fieldMap.get(code);
    }
}

Reference: https://blog.csdn.net/gaoshan12345678910/article/details/84305475

Static static code block
Function: complete the initialization of fieldMap, fields is a reflection method, get all declared fields, and store the variable name and variable value in the map, where the variables are all String types

Reflect to obtain the content of other variable values:
https://blog.csdn.net/zknxx/article/details/46121057

Obtain the name and value of the input parameter through reflection in the section

private Map<String, Object> getParaNameAndValue(ProceedingJoinPoint joinPoint) {
    
    
        Map<String, Object> param = new HashMap<>();
        Object[] paramValues = joinPoint.getArgs();
        Signature signature = joinPoint.getSignature();
        String[] paramNames = null;
        if (signature instanceof CodeSignature) {
    
    
            paramNames = ((CodeSignature) signature).getParameterNames();
        }
        for (int i = 0; i < paramNames.length; i++) {
    
    
            param.put(paramNames[i], paramValues[i]);
        }
        return param;
    }

Guess you like

Origin blog.csdn.net/weixin_38370441/article/details/115265568