【发布时间】: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