How can hibernate access a private field?

杀马特。学长 韩版系。学妹 提交于 2019-12-01 02:09:40

问题


How can hibernate can access a private field/method of a java class , for example to set the @Id ?

Thanks


回答1:


Like Crippledsmurf says, it uses reflection. See Reflection: Breaking all the Rules and Hibernate: Preserving an Object's Contract.




回答2:


Try

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));
   }
}

prints

test= 12345
test.value= 12345
test= 99999
test.value= 99999



回答3:


At a guess I would say that this is done by reflecting on the target type and setting the fields directly using reflection

I am not a java programmer but I believe java has reflection support similar to that of .NET which I do use



来源:https://stackoverflow.com/questions/1113359/how-can-hibernate-access-a-private-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!