2021-04-26

Spring的BeanUtils.copyProperties()的坑

有两个类,ClassA和ClassB,需要把ClassA实例的属性复制到ClassB的实例上

上代码:

package com.trxk.oauth2.authorization.test;

import lombok.Data;
import lombok.ToString;

import java.util.List;

@ToString
@Data
public class ClassA {
    public String outerName;
    public ClassA.InnerClass innerClass;
    public List<InnerClass> clazz;

    @ToString
    @Data
    public static class InnerClass {
        public String InnerName;
    }
}
package com.trxk.oauth2.authorization.test;

import lombok.Data;
import lombok.ToString;

import java.util.List;

@ToString
@Data
public class ClassB {
    public String outerName;
    public ClassB.InnerClass innerClass;
    public List<InnerClass> clazz;

    @ToString
    @Data
    public static class InnerClass {
        public String InnerName;
    }
}

测试

public class Test {
    public static void main(String[] args) {
        ClassA classA = new ClassA();
        classA.outerName = "hahaha";
        ClassA.InnerClass innerClass = new ClassA.InnerClass();
        innerClass.InnerName = "hohoho";
        classA.innerClass = innerClass;

        System.out.println("-----classA--------" +classA.toString());
        ClassB classB = new ClassB();
        BeanUtils.copyProperties(classA, classB);

        System.out.println("-----classB--------" +classB.toString());
    }
}

输出结果

发现ClassA的内部类的属性没有复制到ClassB的实例上

猜你喜欢

转载自blog.csdn.net/qq_43039260/article/details/116143356