How to copy one bean properties to other in Java...
How to copy one bean properties to other in Java...
1)How to copy one Bean properties to other in JAVA:
As we know the Bean class containing the variables with setters and
getters methods. We can access through the getXxx and setXxx methods by
different properties. To copy the properties form one bean to another
they should have same datatypes.
To Run our program the requirements are:
• commons-beanutils , you can download from here http://commons.apache.org/beanutils/
• commons-loging , you can download from here http://commons.apache.org/logging/
• Eclipse
• JDK 1.6
1)Person.java
package com.sunil;
public class Person {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
2)CopyPerson.java
package com.sunil;
public class CopyPerson {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
The TestCopyProperties class will let us test copying properties from
one bean to another. First, it creates a person object(fromBean) and a
copyPerson(toBean) object. It outputs these objects to the console.
Then, it call the BeanUtils.copyProperties() method with toBean as the
first parameter and fromBean as the second parameter. Notice that the
object that is copied to is the first parameter and the object that is
copied from is the second parameter.
In the below program we are copying the properties from person object to copyPerson object using BeanUtils.copyProperties(targer,source) method.
3)TestCopyProperties.java
package com.sunil;
import org.apache.commons.beanutils.BeanUtils;
public class TestCopyProperties {
public static void main(String[] args) throws Exception{
Person person = new Person();
person.setName("Ramu");
person.setAge(24);
CopyPerson copyPerson = new CopyPerson();
copyPerson.setName("Krishna");
copyPerson.setAge(22);
System.out.println("----Before copying the properties----");
System.out.println("--Person Proerpties--");
System.out.println(person.getName());
System.out.println(person.getAge());
System.out.println("--copyPerson Properpties--");
System.out.println(copyPerson.getName());
System.out.println(copyPerson.getAge());
//BeanUtils.copyProperties(destination,source);
BeanUtils.copyProperties(copyPerson,person);
System.out.println("----After Copying the properties from bean one to two----");
//the Person bean properties copied to CopyProperties bean
System.out.println(copyPerson.getName());
System.out.println(copyPerson.getAge());
}
}
0/P:
----Before copying the properties----
--Person Proerpties--
Ramu
24
--copyPerson Properpties--
Krish
26
----After Copying the properties from bean one to two----
Ramu
24
No comments:
Post a Comment