您的位置:首页 > 编程语言 > Java开发

Spring中BeanUtils.copyProperties方法测试

2012-08-11 17:35 351 查看
copyProperties顾名思义是复制属性,就是把A对象的属性复制给B对象的与之相同的属性。下面的属性省略Getter,Setter。

public class UserOne

{

private int id;

private String name;

@Override

public String toString()

{

return id + "......." + name;

}

}

public class UserTwo

{

private int id;

private String name;

private String address;

@Override

public String toString()

{

return id + "......." + name + "........" + address;

}

}

public class UserThree

{

private String id;

private String name;

private String address;

@Override

public String toString()

{

return id + "......." + name + "........" + address;

}

}

import org.springframework.beans.BeanUtils;

public class Test

{

public static void main(String[] args)

{

LessToMore();

MoreToLess();

ArgusMisMatch();

}

// 属性值少的复制给属性值多的,没有被复制到的属性就是该类型的默认值。 结果1......xy......null

public static void LessToMore()

{

UserOne u1 = new UserOne();

u1.setId(1);

u1.setName("xy");

UserTwo u2 = new UserTwo();

BeanUtils.copyProperties(u1, u2);

System.out.println(u2);

}

// 属性值多的复制给属性值少的。结果1......xy

public static void MoreToLess()

{

UserTwo u2 = new UserTwo();

u2.setId(1);

u2.setName("xy");

u2.setAddress("aa");

UserOne u1 = new UserOne();

BeanUtils.copyProperties(u2, u1);

System.out.println(u1);

}

// 报错argument type mismatch。u2的id类型是int,u3的id类型是String

public static void ArgusMisMatch()

{

UserTwo u2 = new UserTwo();

u2.setId(1);

u2.setName("xy");

u2.setAddress("aa");

UserThree u3 = new UserThree();

BeanUtils.copyProperties(u2, u3);

System.out.println(u3);

}

}

总结一下

A对象把与同名且同类型的属性复制给B对象的属性。

没有同名的,B对象的没有被复制值的属性为该类型的默认值。

同名但类型不同,会报错:argument type mismatch
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息