package com.lamp.test;
public class Student {
private String name = "I am private";
public String getName() {
return this.name;
}
}
上面这个类有一个私有属性name但是我们没有为其提供共有方法setName,我们能够改变它的值吗?答案是肯定的,我们可以利用反射技术来实现这个目的
package com.lamp.test;
import java.lang.reflect.Field;
public class ReflectTest {
public static void main(String[] args) throws Exception {
Student student = new Student();
Class<?> clazz = student.getClass();
Field field = clazz.getDeclaredField("name");
//只有通过对Accessible属性设置为true才能对私有变量进行访问,不然会得到一个IllegalAccessException的异常
field.setAccessible(true);
field.set(student, "you are changed");
System.out.println(student.getName());
}
}
我们可以看到私有属性的值被改变了,反射虽然破坏了类的封装性,但是它也是有必要的,没有反射,数据库字段与bean属性之间的映射不能实现,更别谈框架,但是反射也带来了牺牲性能的弊端,所以怎么合理利用就要看具体要求了