利用EZMorph复制Bean
引子
众所周知,在java中对象之间的赋值是地址引用关系,如:
则修改b的属性,a的属性也会跟着修改。
在很多场合下,我们希望克隆出一个新的对象出来,新对象的修改不会影响原有对象,这时我们一般常用的有如下两种方式:
昨晚看到一个新的组件:EZMorph,可以实现同样的功能,这里简单介绍一下。
EZMorph据说起源于json,后来独立出来了,有兴趣的可以到官网(http://ezmorph.sourceforge.net/)上浏览一下。
EZMorph的主要原理
若要将A的属性赋给B,则经过如下步骤:
代码示例
1. 先看几个简单类型的示例
int i = new IntMorpher().morph("123"); Assert.assertEquals(123, i); // true! String str = (String) StringMorpher.getInstance().morph(new Integer(123)); Assert.assertEquals("123", str); // true! Boolean[] bools = (Boolean[]) new ObjectArrayMorpher(new BooleanObjectMorpher()).morph(new String[] { "true","false" }); Assert.assertEquals(Boolean.TRUE, bools[0]); // true! Assert.assertEquals(Boolean.FALSE, bools[1]); // true! MorpherRegistry morperRegistry = new MorpherRegistry(); MorphUtils.registerStandardMorphers(morperRegistry); Integer x = (Integer) morperRegistry.morph(Integer.class, "2"); Assert.assertEquals(new Integer(2), x); // true!
2. 再看一下java.util.Calendar对象
MorpherRegistry morperRegistry = new MorpherRegistry(); MorphUtils.registerStandardMorphers(morperRegistry); Calendar dynaBean = Calendar.getInstance(); // initialized elsewhere System.out.println(dynaBean.getTime()); morperRegistry.registerMorpher(new BeanMorpher(GregorianCalendar.class,morperRegistry)); Calendar myBean = (Calendar) morperRegistry.morph(GregorianCalendar.class, dynaBean);
注意: morperRegistry.registerMorpher( new BeanMorpher( GregorianCalendar.class, morperRegistry ) );
这里必须填写GregorianCalendar类型,如果用Calendar.class就会报出异常,因为EZMorph只能处理public类型的构造方法,而Calendar的构造方法是protected的。这种情况下,最好还是使用Calendar的clone功能。
3. 再看一下,不同对象之间的赋值
Student类
public class Student { private int age; private String name; public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public void hi(int age,String name){ System.out.println("我是"+name+",今年"+age+"岁"); } }
Tearcher
public class Teacher { private String id; private String name; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
将Student对象的name属性赋给Teacher对象的name中
MorpherRegistry morperRegistry = new MorpherRegistry(); Student student = new Student(); student.setName("chb"); morperRegistry.registerMorpher(new BeanMorpher(Teacher.class,morperRegistry)); Teacher teacher = (Teacher) morperRegistry.morph(Teacher.class, student); System.out.println(teacher.getId()); System.out.println(teacher.getName());
输出结果为:
null
chb
可以看出Student和Teacher都有name属性,因此将属性值拷贝过来了,而Student没有id属性,因此Teacher对象的id属性值为空。
总结:对于Bean的copy功能还是不错的,特别是在多线程情况下的应用