Java reflection is used in Android, and java reflection android

Source: Internet
Author: User

Java reflection is used in Android, and java reflection android

Reprinted please indicate the source: http://www.cnblogs.com/cnwutianhao/p/6606687.html

 

If you want to call A private Method B in Class A and use it in class C. Generally, direct call of methods does not work. Some people also say that it is time to turn private into public, but there is a solution in everything, and there is no need to change it to public.

Enter the subject:

There is such a piece of code

public class MainActivity extends AppCompatActivity {    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        method();    }    private void method() {    }}

Now we want to use Junit to test the private method in MainActivity.

If we want to test the private method in MainActivity, direct calling will not work, and Java reflection (Reflect) will be used at this time)

First, create the test file MainActivityTest, which inherits AndroidTestCase

public class MainActivityTest extends AndroidTestCase {}

Then, create the test class testMethod

public void testMethod() throws Exception {}

Complete Test code

public class MainActivityTest extends AndroidTestCase {    public void testMethod() throws Exception {        MainActivity activity = new MainActivity();        Method testMethod = MainActivity.class.getDeclaredMethod("method");        testMethod.setAccessible(true);        testMethod.invoke(activity);    }}

Now, we can use the private method in MainActivity!

 

Follow my Sina Weibo website to learn more about Android development!

Focus on science and technology critics, learn about science and technology, innovation, education, and maximize human wisdom and imagination!

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.