Monday, February 4, 2013

How to Copy properties from one Bean OtherBean

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:

As per shown in the below image you can create the files in Eclipse.



Person.java


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package blog.sbollam;
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;
 }
}
CopyPerson.java


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package blog.sbollam;
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.

TestCopyProperties.java

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package blog.sbollam;
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 Proerpties--");
  System.out.println(copyPerson.getName());
  System.out.println(copyPerson.getAge());
    
  //BeanUtils.copyProperties(destination,source);
  BeanUtils.copyProperties(copyPerson,person);
    
  System.out.println("----Person to CopyPerson----");
  //the Person bean properties copied to CopyProperties bean
  System.out.println(copyPerson.getName());
  System.out.println(copyPerson.getAge());
 }
}

Output:

No comments:

Post a Comment