Imagine if you could easily invoke a private method of a class, would you say that your encapsulation is not valid? Recently looking at the reflection mechanism of Java, found that can use Java reflection mechanism to invoke other classes of private methods, as to what this can do, then see the wisdom of people.
The 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, 9:53:49 PM * Class description/public class Reflectiontest {public STA tic void Setobjectcolor (Object obj) throws SecurityException, Nosuchmethodexception, IllegalArgumentException,
Illegalacces***ception, invocationtargetexception{Class cls = Obj.getclass ();
Gets the private method of the class methods approach = Cls.getdeclaredmethod ("Privatemethod", null); Method.setaccessible (TRUE);
No settings will error//Call the method Method.invoke (obj, null); public static void Main (String args[]) throws SecurityException, IllegalArgumentException, Nosuchmethodexception, Ille
Galacces***ception, invocationtargetexception{Setobjectcolor (New MyTest ());
}//Test classes Class mytest{public void Setmytest () {System.out.println ("setmytest");
The private method of the/** class **/private void Privatemethod () {System.out.println ("Invoke private Methods");
}
}
The above this article uses the Java reflection mechanism to invoke the class the Private method (recommendation) is the small series to share to everybody's content, hoped can give everybody a reference, also hoped that everybody supports the cloud habitat community.