如何让Hibernate可以访问Java类的私有字段/方法,比如设置@Id?谢谢。
像Crippledsmurf所说的那样,它使用了反射。请参见Reflection: Breaking all the Rules和Hibernate: Preserving an Object's Contract。
尝试
import java.lang.reflect.Field;
class Test {
private final int value;
Test(int value) { this.value = value; }
public String toString() { return "" + value; }
}
public class Main {
public static void main(String... args) throws NoSuchFieldException, IllegalAccessException {
Test test = new Test(12345);
System.out.println("test= "+test);
Field value = Test.class.getDeclaredField("value");
value.setAccessible(true);
System.out.println("test.value= "+value.get(test));
value.set(test, 99999);
System.out.println("test= "+test);
System.out.println("test.value= "+value.get(test));
}
}
打印
test= 12345
test.value= 12345
test= 99999
test.value= 99999