private int id;
private String name;
private int age;
public Employee() {
}
public Employee(int id,String name,int age) {
this.id = id;
this.name = name;
this.age = age;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
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;
}
//通過Comparable接口自定義對象的比較規則
public int compareTo(Employee o) {
if(id>o.id){
return 1;
}else if(id<o.id){
return -1;
}
return 0;
}
//通過反射動態設置類的私有域
public static void main(String[] args) {
Employee e = new Employee();
Class cla = e.getClass();
System.out.println("類的標準名字爲:"+cla.getCanonicalName());
try {
Field id = cla.getDeclaredField("id");
System.out.println("設置前的ID爲:"+e.getId());
id.setAccessible(true);
id.setInt(e, 10);
System.out.println("設置後的ID爲:"+e.getId());
} catch (NoSuchFieldException e1) {
e1.printStackTrace();
} catch (SecurityException e1) {
e1.printStackTrace();
} catch (IllegalArgumentException e1) {
e1.printStackTrace();
} catch (IllegalAccessException e1) {
e1.printStackTrace();
}
}
}
執行結果:
類的標準名字爲:order.Employee
設置前的ID爲:0
設置後的ID爲:10