Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can hibernate access a private field?

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

Thanks

like image 920
Pierre Avatar asked Jul 11 '09 09:07

Pierre


People also ask

How does Hibernate access private fields?

Basically Hibernate uses Reflection which can gain access to private instance vairables as well as private methods.

How do I access private field?

If we want to access Private Field and method using Reflection we just need to call setAccessible(true) on the field or method object which you want to access. Class. getDeclaredField(String fieldName) or Class. getDeclaredFields() can be used to get private fields.

Can fields be private?

Fields can be marked as public, private, protected, internal, protected internal, or private protected. These access modifiers define how users of the type can access the fields. For more information, see Access Modifiers. A field can optionally be declared static.

Should fields be public or private?

Fields should be declared private unless there is a good reason for not doing so. One of the guiding principles of lasting value in programming is "Minimize ripple effects by keeping secrets." When a field is private , the caller cannot usually get inappropriate direct access to the field.


3 Answers

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

like image 166
Matthew Flaschen Avatar answered Nov 04 '22 12:11

Matthew Flaschen


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
like image 44
Peter Lawrey Avatar answered Nov 04 '22 12:11

Peter Lawrey


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

like image 22
Crippledsmurf Avatar answered Nov 04 '22 11:11

Crippledsmurf