The use of Java reflection in Android

Source: Internet
Author: User

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

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.