着实list内里的两个类也都是重写的内部类,他们也是差异的,其时他们却顺遂copy已往了,为什么呢?由于java的泛型只在编译期起浸染,在运行期,list属性就是一个存放Object的荟萃,在copy后,MixAddRequest的orders属性着实是一个Order类的荟萃,但却不是本身内部类的荟萃,是AddRequest的内部类Order的荟萃,但由于对方是理会json的,以是没有产生错误。。。
总结
1. Spring的BeanUtils的CopyProperties要领必要对应的属性有getter和setter要领;
2. 假如存在属性完全沟通的内部类,可是不是统一个内部类,即别离属于各自的内部类,则spring会以为属性差异,不会copy;
3. 泛型只在编译期起浸染,不能依赖泛型来做运行期的限定;
4. 最后,spring和apache的copy属性的要领源和目标参数的位置正好相反,以是导包和挪用的时辰都要留意一下。
最后的最后
附上spring的源码,getWriteMethod是jdk的要领,会去取set开头的要领,以是没有setter要领是不可滴。
- privatestaticvoid copyProperties(Object source, Object target, @Nullable Class<?> editable, @Nullable String... ignoreProperties) throws BeansException {
- Assert.notNull(source, "Source must not be null");
- Assert.notNull(target, "Target must not be null");
- Class<?> actualEditable = target.getClass();
- if (editable != null) {
- if (!editable.isInstance(target)) {
- throw new IllegalArgumentException("Target class [" + target.getClass().getName() + "] not assignable to Editable class [" + editable.getName() + "]");
- }
-
- actualEditable = editable;
- }
-
- PropertyDescriptor[] targetPds = getPropertyDescriptors(actualEditable);
- List<String> ignoreList = ignoreProperties != null ? Arrays.asList(ignoreProperties) : null;
- PropertyDescriptor[] var7 = targetPds;
- int var8 = targetPds.length;
-
- for(int var9 = 0; var9 < var8; ++var9) {
- PropertyDescriptor targetPd = var7[var9];
- Method writeMethod = targetPd.getWriteMethod();
- if (writeMethod != null && (ignoreList == null || !ignoreList.contains(targetPd.getName()))) {
- PropertyDescriptor sourcePd = getPropertyDescriptor(source.getClass(), targetPd.getName());
- if (sourcePd != null) {
- Method readMethod = sourcePd.getReadMethod();
- if (readMethod != null && ClassUtils.isAssignable(writeMethod.getParameterTypes()[0], readMethod.getReturnType())) {
- try {
- if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
- readMethod.setAccessible(true);
- }
-
- Object value = readMethod.invoke(source);
- if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {
- writeMethod.setAccessible(true);
- }
-
- writeMethod.invoke(target, value);
- } catch (Throwable var15) {
- throw new FatalBeanException("Could not copy property '" + targetPd.getName() + "' from source to target", var15);
- }
- }
- }
- }
- }
-
- }
(编辑:河北网)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|