Test class private members with Java reflection

Source: Internet
Author: User

In the Java development phase, because of the pursuit of architectural specifications and follow the design principles, so to use the private and protected modifiers to define the class member methods, variables, constants, which makes the code encapsulation, cohesion, etc., but in the testing phase will cause some inconvenience. Through the reflection mechanism of Java, this problem can be solved well.

Reflectutil.java
/** * @author yumin * @since 2015-03-02 14:52 */public class Reflectutil {private Reflectutil () {}//part        Code slightly public static object InvokeMethod (Object object, String methodName, class[] parametertypes, object[] args) {        Object result = null; if (null! = object) {try {method = Getdeclaredmethod (object, MethodName, Parametertypes                );            result = Method.invoke (object, args);                } catch (Nosuchmethodexception e) {//...} catch (Illegalaccessexception e) { //......            }        catch (InvocationTargetException e) {//...}    } return result; public static Method Getdeclaredmethod (Object object, String methodName, class[] parametertypes) throws Nosuchmethode        xception {method = null;        if (null! = Object) {method = Object.getclass (). Getdeclaredmethod (MethodName, parametertypes);    Method.setaccessible (TRUE);    } return method; }}
Reflectutiltest.java
/** * @author yumin * @since 2015-03-02 14:53 */public class Reflectutiltest {//Part code slightly @Test public void        Testinvokemethod () throws Exception {String whatisyourname = null;        String howoldareyou = null;        String name = "Yumin";        int age = 18;        person person = new person ();        Whatisyourname = (String) reflectutil.invokemethod (person, "whatisyourname", NULL, NULL);        Howoldareyou = (String) reflectutil.invokemethod (person, "howoldareyou", New Class[]{int.class}, New Object[]{age});        Assert.assertequals (person.whatisyourname + name, whatisyourname);    Assert.assertequals (person.howoldareyou + age, howoldareyou);        public class Person {public static final String whatisyourname = ' My name is ';        public static final String howoldareyou = "I ' m"; Private String name = "Yumin";        Name public void SetName (String name) {this.name = name; } private String Whatisyourname (){return whatisyourname + name;        } private String howoldareyou (int age) {return howoldareyou + age; }    }}

It can be seen through the Java reflection mechanism, to achieve the private and protected modified methods and properties of the call, value, value and other read and write operations, not destroying the original code can also complete the unit test of private members. It is important to note that it is recommended to use only in test scenarios, to make it easy to invoke private members of the class through reflection in the code logic that is released in the production environment, thus destroying the original class design, producing unpredictable results and polluting the architecture resulting in subsequent difficult maintenance.

For more detailed code, see: https://github.com/wangym/java-common/

Test class private members with Java reflection

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.