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!