Invoking a private method of a class using the Java Reflection Mechanism (recommended) _java

Source: Internet
Author: User
Tags reflection

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.