[Blankj/AndroidUtilCode]类似java后台的beanutils.copyproperty的方法

2024-07-15 559 views

回答

5

+1,一直都在等一个这样的类

5

Android 这边和 spring 的 jdk 还是有区别的,比较难实现

3

@Blankj 用反射可以实现,我这边项目中只是实现了基本代码,很多情况没有考虑。通过属性的get,set方法调用,这里有个基本类可以参考下:

private static void copyPropertiesExclude(Object from, Object to) throws Exception {
        Method[] fromMethods = from.getClass().getDeclaredMethods();
        Method[] toMethods = to.getClass().getDeclaredMethods();
        Method fromMethod, toMethod;
        String fromMethodName, toMethodName;
        for (Method fromMethod1 : fromMethods) {
            fromMethod = fromMethod1;
            fromMethodName = fromMethod.getName();
            boolean isStartMethod = fromMethodName.startsWith("is");
            if (!(fromMethodName.startsWith("get") || isStartMethod) || fromMethodName.contains("getId"))
                continue;
            //排除列表检测
            toMethodName = "set" + fromMethodName.substring(isStartMethod ? 2 : 3);
            toMethod = findMethodByName(toMethods, toMethodName);
            if (toMethod == null)
                continue;
            Object value = fromMethod.invoke(from);
            if (value == null)
                continue;
            //集合类判空处理
            if (value instanceof Collection) {
                Collection newValue = (Collection) value;
                if (newValue.size() <= 0)
                    continue;
            }
            toMethod.invoke(to, value);
        }
    }
2

使用的场景还是比较广泛的,特别是碰到本地建立数据库,需要保存数据的时候。

5

+1,+1,+1,这个非常常用

2

我觉得重新重新json一下就ok了,不用这么麻烦