欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

java利用reflectasm反射 博客分类: Java reflectasmjava反射 

程序员文章站 2024-03-16 12:11:58
...
import java.lang.reflect.Field;
import java.util.concurrent.ConcurrentMap;
import com.esotericsoftware.reflectasm.MethodAccess;
import com.google.common.collect.Maps;

public class ReflectUtil {
    private static final ConcurrentMap<Class<?>, MethodAccess> localCache = Maps.newConcurrentMap();

    private ReflectUtil() {

    }

    public static String upperFirstChar(String str) {
        if (str == null || "".equals(str)) {
            return str;
        }
        char[] cs = str.toCharArray();
        cs[0] -= 32;
        return String.valueOf(cs);
    }
    
    public static Object setProperty(Object clazz, String fname, Object fvalue) {
        if (clazz == null) {
            throw new IllegalArgumentException("No bean specified");
        }
        if (fname == null) {
            throw new IllegalArgumentException("No name specified for bean class '" + clazz.getClass() + "'");
        }
        return get(clazz.getClass()).invoke(clazz, "set" + upperFirstChar(fname), fvalue);
    }

    public static Object getProperty(Object clazz, String fname) {
        if (clazz == null) {
            throw new IllegalArgumentException("No bean specified");
        }
        if (fname == null) {
            throw new IllegalArgumentException("No name specified for bean class '" + clazz.getClass() + "'");
        }
        return get(clazz.getClass()).invoke(clazz, "get" + upperFirstChar(fname));
    }

    public static MethodAccess get(Class<?> clazz) {
        if (localCache.containsKey(clazz)) {
            return localCache.get(clazz);
        }

        MethodAccess methodAccess = MethodAccess.get(clazz);
        localCache.putIfAbsent(clazz, methodAccess);
        return methodAccess;
    }

    public static <F, T> void copyPropertiesIgnoreNull(F from, T to) {
        copyProperties(from, to, true);
    }

    public static <F, T> void copyProperties(F from, T to) {
        copyProperties(from, to, false);
    }

    public static <F, T> void copyProperties(F from, T to, boolean ignoreNull) {
        MethodAccess fromMethodAccess = get(from.getClass());
        MethodAccess toMethodAccess = get(to.getClass());
        Field[] fromDeclaredFields = from.getClass().getDeclaredFields();
        for (Field field : fromDeclaredFields) {
            String name = field.getName();
            try {
                Object value = fromMethodAccess.invoke(from, "get" + upperFirstChar(name));
                if (ignoreNull && value == null) {
                    continue;
                }
                toMethodAccess.invoke(to, "set" + upperFirstChar(name), value);
            } catch (Exception e) {
            }
        }
    }
}