Get the value of an object through reflection

  In the work, it is inevitable to obtain the value of an attribute of the object through reflection, so as to carry out the next operation. The following reflection tools implement such a function.

Method 1: Obtaining through object reflection

package com.bijian.test;

import java.lang.reflect.Field;

/**
 * Reflection to get object attribute value tool class
 */
public class ParamsReflectUtil {

	public static Object getFieldValue(Object obj, String field) {

		Class<?> claz = obj.getClass();
		Field f = null;
		Object fieldValue = null;
		try {
			Field[] fields = claz.getDeclaredFields();
			for (int i = 0; i < fields.length; i++) {
				if (fields[i].getName().equals(field)) {
					f = claz.getDeclaredField(field);
					f.setAccessible(true);
					fieldValue = f.get(obj);
				}
			}
		} catch (Exception e) {
			System.out.println(e.getStackTrace());
		}
		return fieldValue;
	}
}

  Call example:

String custNo = (String) ParamsReflectUtil.getFieldValue(request.getData(), "custNo");

  If request.getData() here is a json string, or further, request.getData() is a general json string, it is impossible (or exhaustive) to map it to a java object one by one, we can use json tool to obtain it, as shown in the following method.

 

Method 2: Obtained through the Json tool

import java.util.Map;
import java.util.TreeMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

/**
 * Attribute (object) value reflection acquisition tool class
 */
public class ParamsReflectUtil {
    
    private final static Logger logger = LoggerFactory.getLogger(ParamsReflectUtil.class);
    
    public static Object getFieldValue(String jsonStr, String field) {
        
        JSONObject jsonObject = JSON.parseObject(jsonStr);
        Object fieldValue = null;
        for (Iterator iter = jsonObject.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            if(name.equals(field)) {
                fieldValue = jsonObject.get(name);
            }
        }
        return fieldValue;
    }
}

Call example:

String custNo = (String) ParamsReflectUtil.getFieldValue(request.getData(), "custNo");

 

Reference: http://blog.csdn.net/starryninglong/article/details/60468440

https://zhidao.baidu.com/question/1754507934238487268.html

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326435631&siteId=291194637