【问题标题】:deep copy using reflection java使用反射java进行深度复制
【发布时间】:2020-08-03 15:15:09
【问题描述】:

我无法使用反射从类字段中获取容器。我尝试了以下方法,但出现异常:

Exception in thread "main" java.lang.UnsupportedOperationException
    at java.util.AbstractList.add(AbstractList.java:148)
    at java.util.AbstractList.add(AbstractList.java:108)
    at java.util.Collections.addAll(Collections.java:5455)
public static void copy(Object from, Object to) throws NoSuchFieldException, IllegalAccessException {
        Class<?> fromClass = from.getClass();
        Class<?> toClass = to.getClass();
        Field[] sourceFields = fromClass.getDeclaredFields();
        for (Field fromField : sourceFields) {
            Field toField = toClass.getDeclaredField(fromField.getName());
            toField.setAccessible(true);
            fromField.setAccessible(true);
            if (fromField.getType().equals(toField.getType())) {
                if (!(fromField.getType() == String.class || fromField.getType().isPrimitive())) {
                        if (fromField.getType().isAssignableFrom(List.class)) {
                            List list = (List) fromField.get(from);
                            List list1 = (List) toField.get(to);
                            Collections.addAll(list1,list);
                            toField.set(to, fromField.get(from));
                        } else if (fromField.getType().isAssignableFrom(Set.class)) {
                            Set set = (Set) fromField.get(from);
                            Set set1 = (Set) toField.get(to);
                            set1.clear();
                            set.addAll(set1);
                            toField.set(to, fromField.get(from));
                        }
                } else {
                    toField.set(to, fromField.get(from));
                }
            }
        }
    }

我不想使用通过序列化复制的方法,我对反射感兴趣。

【问题讨论】:

  • 您尝试添加的列表似乎不支持add 操作。您可能想要调试它并查看您正在处理的List 的实现。
  • 拿toField的getClass看看是什么List实现。某些实现不支持add(如Arrays.asList)。实现类是 AbstractListClass 的子类,没有自己的 add,你可以检查一下。

标签: java reflection deep-copy


【解决方案1】:

我希望你这样做是为了训练?如果没有,那就使用一些开源库,这比你想象的要困难得多 - check this

您的问题是您要添加到 to 列表中,而 to 列表是不支持添加的实现(顺便说一句,您忽略了结果)。我建议创建一个新列表并重新分配它,而不是添加到现有列表中。

List list = (List) fromField.get(from);
List list1 = (List) toField.get(to);
List newList = new ArrayList();
if(list != null)
  Collections.addAll(newList,list);
if(list1 != null)
  Collections.addAll(newList,list1);
toField.set(to, newList);

Set 类似 - 您当前的Set 代码没有任何意义,它在Class 对象上运行。

【讨论】:

    猜你喜欢
    • 2013-03-11
    • 1970-01-01
    • 2013-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多