Just imagine, if you can easily call a private method of a class, then does it mean that your encapsulation has expired? Recently, I was looking at the reflection mechanism of Java and found that it can actually use the reflection mechanism of Java to call private methods of other classes. As for what this can do, it is up to people's opinions. .
A simple example code I wrote is as follows:
import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;/** * @author thomaslwq * @version Creation time: Sep 4, 2012 9:53:49 PM * Class Description*/public class ReflectionTest { public static void setObjectColor(Object obj) throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAcces***ception, InvocationTargetException{ Class cls = obj.getClass(); //Get private method of the class Method method = cls.getDeclaredMethod("privateMethod", null); method.setAccessible(true); //An error will be reported without setting//Call this method.invoke(obj, null); } public static void main(String args[]) throws SecurityException, IllegalArgumentException, NoSuchMethodException, IllegalAcces***ception, InvocationTargetException{ setObjectColor(new MyTest()); }} //Test class MyTest{ public void setMyTest(){ System.out.println("setMyTest"); } /** Private method of class**/ private void privateMethod(){ System.out.println("Private Method"); } }The above private method (recommended) that uses the Java reflection mechanism to call the class 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.