`BeanUtils.copyProperties`没有复制任何字段。

huangapple 未分类评论47阅读模式
英文:

BeanUtilsBeans copyProperties not copying any fields

问题

以下是翻译好的内容:

我正在尝试使用Apache Commons BeanUtils 来将源对象的字段复制到目标对象。然而,在测试我的代码时,属性根本没有被复制。以下是我使用的代码:

public class CopyUtilTest {

    public void copySourceToDestination(Object destinationObject, Object sourceObject) throws ApiException {
        BeanUtilsBean beanUtil = new BeanUtilsBean();
        try {
            beanUtil.copyProperties(destinationObject, sourceObject);
        } catch (InvocationTargetException | IllegalAccessException e) {
            throw new ApiException("在使用[NullAwarePropertyCopy]复制属性时出错");
        }
    }

    @Test
    public void testCopy() throws ApiException {
        A source = new A();
        source.setA("John");
        source.setB(23);

        B target = new B();

        copySourceToDestination(target, source);
        System.out.println(target.getA() + " " + target.getB());
    }

}

@Getter
@Setter
class A {
    String a;
    int b;
}

@Getter
@Setter
class B {
    String a;
    int b;
}

当我在 Junit 中运行此测试时,我得到的输出是 null 0,这明显表明字段没有被复制。为什么会出现这种情况呢?

英文:

I am trying to use Apache Commons BeanUtils to copy fields from a source object to a destination object. However, when testing my code, the properties are not copied at all. Following is the code I am using

public class CopyUtilTest {

    public void copySourceToDestination(Object destinationObject, Object sourceObject) throws ApiException {
        BeanUtilsBean beanUtil = new BeanUtilsBean();
        try {
            beanUtil.copyProperties(destinationObject, sourceObject);
        } catch (InvocationTargetException | IllegalAccessException e) {
            throw new ApiException("Error in copying properties using [NullAwarePropertyCopy]");
        }
    }

    @Test
    public void testCopy() throws ApiException {
        A source = new A();
        source.setA("John");
        source.setB(23);

        B target = new B();

        copySourceToDestination(target, source);
        System.out.println(target.getA()+" "+target.getB());
    }

}

@Getter
@Setter
class A {
    String a;
    int b;
}

@Getter
@Setter
class B {
    String a;
    int b;
}

The output I get when running this test in Junit is null 0 which clearly indicates that the fields have not been copied. Why could this be happening?

huangapple
  • 本文由 发表于 2020年7月23日 15:58:55
  • 转载请务必保留本文链接:https://java.coder-hub.com/63049531.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定