We know that a Java application cannot access the private method of a persisted class, but Hibernate does not have this restriction to access various levels of methods, such as private, default, protected, public. How does hibernate implement this function? The answer is to use the Java reflection mechanism as follows:
Import java.lang.reflect.InvocationTargetException;
Import Java.lang.reflect.Method;
public class Reflectdemo {public
static void Main (string[] args) throws Exception {Method method
= Packageclazz. Class.getdeclaredmethod ("Privilegedmethod", New Class[]{string.class,string.class});
Method.setaccessible (true);
Method.invoke (New Packageclazz (), "452345234", "q31234132");
}
Class Packageclazz {
private void Privilegedmethod (String invokername,string adb) {
System.out.println ("--- "+invokername+"----"+adb)";
}
The output is:---452345234----q31234132
We see that using the reflection mechanism of Java, even private methods can be invoked to use. But I came up with a question--that the private method can be invoked, what's the point of encapsulation?
The above Java in the use of reflection to invoke another kind of private method of a simple example is the small series to share all the content of everyone, hope to give you a reference, but also hope that we support the cloud habitat community.