能够分析类的能力的程序称为“反射”。反射机制的功能及其强大,它可以用来:
1、在运行时分析类的能力
2、在运行时查看类的对象
下面的代码利用发射机制修改对象的私有属性:
public class Employee implements Cloneable{
private String name = "";
private double salary = 0.0;
public Employee(String name,double salary){
this(name);
this.salary = salary;
}
public String getName() {
return name;
}
public double getSalary() {
return salary;
}
}
public class Main {
public static void main(String[] args) throws Exception{
Employee employee = new Employee("张三",12000);
Class cl = employee.getClass();//获取Class对象
Field field = cl.getDeclaredField("salary");//获取salary属性
field.setAccessible(true);//覆盖私有属性的访问控制权限
System.out.println("修改前的Salary:"+employee.getSalary());
field.set(employee,13000);//利用Field的set方法修改私有属性值
System.out.println("修改后的Salary:"+employee.getSalary());
}
}
实际结果:
如有错误,敬请指正