Dynamically obtain class attributes and attribute values through reflection and assign corresponding attribute values of one class to another class

Not much nonsense, go directly to the code method. This method is to pass in a collection of any type T of generic type, and then use reflection to get the properties of the object of type T from the collection, then set to the object of type E and return the object E. Dear friends, you can use this method I wrote to make any transformation that suits your needs.

/**
 *
 * @param from
 * @param e
 * @param <T>  传入的对象
 * @param <E>  输出的对象
 * @return  把集合为T的 类型通过反射,进行对应的赋值到e的相同属性中去
 * @throws IllegalAccessException
 * @throws InstantiationException
 * @throws ClassNotFoundException
 * @throws NoSuchFieldException
 */
public <T, E> E getArrObjByNames(ArrayList<T> from, E e) throws IllegalAccessException, InstantiationException, ClassNotFoundException, NoSuchFieldException {
    // 被赋值对象
    List<Field> fields = Arrays.asList(e.getClass().getDeclaredFields());
    List<String> list = new ArrayList<>();
    fields.forEach(field -> list.add(field.getName()));
    for (T t : from) {
        System.out.println(t);
        for (int i = 0; i < t.getClass().getDeclaredFields().length; i++) {
            String str = t.getClass().getDeclaredFields()[i].getName();
            // 因为FIELDNUM 是静态的 注意getDeclaredField 和 getField 的不同
            if (!"FIELDNUM".equals(str) && list.contains(str)) {
                Field f = e.getClass().getDeclaredField(str);
                // 
                Field f1 = t.getClass().getDeclaredField(str);
                f.setAccessible(true);
                f1.setAccessible(true);
                f.set(e, f1.get(t));
            }
        }
    }
    return e;
}

Note the get method in the Field class above. What to pass in f.get(obj) is the obj object where the Field is located.

Guess you like

Origin blog.csdn.net/AntdonYu/article/details/105450902
Recommended