Spring中BeanUtils.copyProperties方法測試
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
最後更新:2017-04-03 07:57:24