We know that Java applications cannot access private methods of persistent classes, but Hibernate does not have this limitation. It can access various levels of methods, such as private, default, protected, public. How does Hibernate implement this function? The answer is to use JAVA's 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 result is: ---452345234---q31234132
We see that using Java's reflection mechanism, even the private method can be called and used. However, I have a question - even if the private method can be called, what's the point of encapsulation?
The above simple example of using reflection to call another type of private method in Java is all the content I share with you. I hope you can give you a reference and I hope you can support Wulin.com more.