Created
April 30, 2013 07:03
-
-
Save adilkurniaramdan/5487070 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Employee { | |
private String id; | |
private String firstName; | |
private String lastName; | |
private String address; | |
private int age; | |
//setter getter are hidden | |
} | |
public class User { | |
private String id; | |
private String firstName; | |
private String lastName; | |
private String address; | |
private int age; | |
//setter getter are hidden | |
} | |
import java.lang.reflect.Field; | |
public class MainApp { | |
public static void main(String[] args) { | |
Employee employee = new Employee(); | |
employee.setId("1"); | |
employee.setFirstName("adil"); | |
employee.setLastName("ramdan"); | |
employee.setAge(22); | |
employee.setAddress("bandung"); | |
System.out.println(employee.toString()); | |
User user = new User(); | |
migratingValue(employee, user); | |
user.setId("10"); | |
System.out.println(user.toString()); | |
} | |
public static User migratingValue(Employee employee, User user) { | |
Class employeeClass = employee.getClass(); | |
Class userClass = User.class; | |
Field[] arrField = employeeClass.getDeclaredFields(); | |
for (Field field : arrField) { | |
field.setAccessible(true); | |
try { | |
if (!field.getName().equals("id")) { | |
Field userField = userClass.getDeclaredField(field | |
.getName()); | |
userField.setAccessible(true); | |
userField.set(user, field.get(employee)); | |
} | |
} catch (Exception e) { | |
// TODO Auto-generated catch block | |
} | |
} | |
return user; | |
} | |
} | |
//Hasilnya adalah sebagai berikut : | |
Employee [id=1, firstName=adil, lastName=ramdan, address=bandung, age=22] | |
User [id=10, firstName=adil, lastName=ramdan, address=bandung, age=22] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment