All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.robe.common.utils.FieldReflection Maven / Gradle / Ivy

There is a newer version: 0.5.0.0-1039
Show newest version
package io.robe.common.utils;

import com.google.common.collect.ImmutableSet;

import java.lang.reflect.Field;
import java.util.concurrent.ConcurrentHashMap;

/**
 * A class which helps field operations by reflectasm library.
 * It also has cache support for class fields.
 */
public class FieldReflection {

    private FieldReflection() {

    }

    private static final ConcurrentHashMap, ImmutableSet> cache = new ConcurrentHashMap();

    private static final ImmutableSet get(Class clazz) {
        if (!cache.containsKey(clazz)) {
            Field[] fields = clazz.getDeclaredFields();
            for (Field field : fields) {
                field.setAccessible(true);
            }
            cache.put(clazz, ImmutableSet.copyOf(fields));
            return cache.get(clazz);
        }
        return cache.get(clazz);
    }

    public static final  void copy(T src, T dest) {
        ImmutableSet fa = get(src.getClass());
        for (Field field : fa) {
            try {
                field.set(dest, field.get(src));
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
    }

    public static final  void mergeRight(T src, T dest) {
        ImmutableSet fa = get(src.getClass());
        for (Field field : fa) {
            try {
                Object value = field.get(src);
                if (value == null)
                    continue;
                field.set(dest, value);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
    }

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy