【发布时间】:2010-11-09 22:42:19
【问题描述】:
hibernate 如何访问 java 类的私有字段/方法,例如设置@Id?
谢谢
【问题讨论】:
标签: java hibernate reflection field private
hibernate 如何访问 java 类的私有字段/方法,例如设置@Id?
谢谢
【问题讨论】:
标签: java hibernate reflection field private
就像 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
【讨论】:
我猜我会说这是通过反射目标类型并直接使用反射设置字段来完成的
我不是 java 程序员,但我相信 java 具有类似于我使用的 .NET 的反射支持
【讨论】: