class Coder {
private String name = "";
private int age = 0;
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public void cloneFrom(Coder coder) {
Field[] declaredFieldsFrom = coder.getClass().getDeclaredFields();
Field[] declaredFields = getClass().getDeclaredFields();
for (final Field declaredFieldFrom : declaredFieldsFrom) {
for (final Field declaredField : declaredFields) {
if (declaredFieldFrom.getName().equals(declaredField.getName())) {
try {
declaredField.set(this, declaredFieldFrom.get(coder));
} catch (IllegalAccessException e) {
e.printStackTrace();
declaredField.setAccessible(true);
declaredFieldFrom.setAccessible(true);
try {
declaredField.set(this, declaredFieldFrom.get(coder));
} catch (IllegalAccessException ex) {
ex.printStackTrace();
}
declaredField.setAccessible(false);
declaredFieldFrom.setAccessible(false);
}
}
}
}
}
}
网友评论