Reprint Please specify source: http://www.cnblogs.com/cnwutianhao/p/6606687.html
Java developers or Android developers often encounter such a problem, if we want to invoke a Class A private method B, and then used in Class C. The usual method of direct invocation is not feasible. Some people say that the private to the public will be finished, but everything has a solution, do not change to public.
Go to the Chase:
There is a code like this
Public class extends appcompatactivity { @Override protectedvoid onCreate (Bundle Savedinstancestate) { super. OnCreate (savedinstancestate); Setcontentview (r.layout.activity_main); Method (); } Private void method () { }}
Now we want to test the private method in mainactivity with JUnit.
If we want to test the private method in Mainactivity, the direct call is not working, then we use the Java Reflection (Reflect)
First, create a test file mainactivitytest, inherit Androidtestcase
Public class extends Androidtestcase {}
Then, create the test class TestMethod
Public void throws Exception {}
Full Test code
Public class extends androidtestcase { publicvoidthrows Exception { new mainactivity (); = Mainactivity. class. Getdeclaredmethod ("method"); Testmethod.setaccessible (true); Testmethod.invoke (activity);} }
At this point, we can use the private method in Mainactivity!
Follow me on Sina Weibo for more information on Android development!
Focus on technology critics, learn about technology, innovation, education and maximizing human intelligence and imagination!
The use of Java reflection in Android