【问题标题】:How can hibernate access a private field?hibernate如何访问私有字段?
【发布时间】:2010-11-09 22:42:19
【问题描述】:

hibernate 如何访问 java 类的私有字段/方法,例如设置@Id?

谢谢

【问题讨论】:

    标签: java hibernate reflection field private


    【解决方案1】:

    就像 Crippledsmurf 所说,它使用反射。请参阅Reflection: Breaking all the RulesHibernate: Preserving an Object's Contract

    【讨论】:

      【解决方案2】:

      试试

      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
      

      【讨论】:

        【解决方案3】:

        我猜我会说这是通过反射目标类型并直接使用反射设置字段来完成的

        我不是 java 程序员,但我相信 java 具有类似于我使用的 .NET 的反射支持

        【讨论】:

          猜你喜欢
          • 2012-06-07
          • 1970-01-01
          • 1970-01-01
          • 2021-12-15
          • 2013-12-17
          • 2012-01-23
          • 2015-03-07
          • 2012-10-03
          • 1970-01-01
          相关资源
          最近更新 更多