用反射操作数据

  通过反射设置数据,获取数据。代码如下示例。

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

/**
 * 工具类
 * Created by doudou on 2018/1/19.
 */
public class ReflectionUtil {

    private ReflectionUtil() {
        throw new AssertionError();
    }

    /**
     * 通过反射取对象指定字段(属性)的值
     * @param target 目标对象
     * @param fieldName 字段的名字
     * @return  字段的值
     */
    public static Object getValue(Object target, String fieldName) {
        Class<?> clazz = target.getClass();
        String[] fields = fieldName.split("\.");

        try {
            for (int i = 0; i < fields.length - 1; i++) {
                Field field = clazz.getDeclaredField(fields[i]);
                field.setAccessible(true);
                target = field.get(target);
                clazz = target.getClass();
            }
            Field field = clazz.getDeclaredField(fields[fields.length - 1]);
            field.setAccessible(true);
            return field.get(target);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static Object setValue(Object target, String fieldName) {
        Class<?> clazz = target.getClass();
        String[] fields = fieldName.split("\.");
        try {
            for (int i = 0; i < fields.length - 1; i++) {
                Field field = clazz.getDeclaredField(fields[i]);
                field.setAccessible(true);
                Object value = field.get(target);
                if (value == null) {
                    Constructor<?> c = field.getType().getDeclaredConstructor();
                    c.setAccessible(true);
                    value = c.newInstance();
                    field.set(target, value);
                }
                target = value;
                clazz = target.getClass();
                Field f = clazz.getDeclaredField(fields[fields.length - 1]);
                f.setAccessible(true);
                f.set(target, value);
            }
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }
        return null;
    }
}
原文地址:https://www.cnblogs.com/xinlichai0813/p/8317218.html