class Person implements Cloneable{
String name;
int age;
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public Person(int age, String name) {
this.name = name;
this.age = age;
}
public Person() {
}
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;
}
@Override
public Person clone() throws CloneNotSupportedException {
return (Person) super.clone();
}
@Override
public void finalize() throws Throwable {
System.out.println("finalize...");
super.finalize();
}
}
public class SubPerson extends Person {
String name;
int age;
@Override
public String toString() {
return super.toString()+"SubPerson{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
public static void main(String[] args) {
try {
SubPerson person = new SubPerson();
Field[] allFields = FieldUtils.getAllFields(person.getClass());
int a = 10;
for (Field field : allFields) {
if(field.getName() == "age"){
field.setAccessible(true);
field.set(person, a++);
}
}
System.out.println(person);
} catch (Exception e) {
e.printStackTrace();
}
}
输出结果:Person{name=‘null’, age=11}SubPerson{name=‘null’, age=10}