javaandroiddexclassloader

How to get current value of field in Activity when using DexClassLoader?


I have a field in MainActivity like this

public class MainActivity extends AppCompatActivity {

private static String field = "abc";

private void setField(Intent intent) {
    String field2;
    if (intent != null && (field2 = intent.getStringExtra("field")) != null) {
        field = field2;

    }
}

/* access modifiers changed from: protected */
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView((int) R.layout.activity_main);
    setField(getIntent());
....

and I load method from Dex file with this code

Class<?> classToLoad = new DexClassLoader(codeFile.getAbsolutePath(), tmpDir.getAbsolutePath(), (String) null, ClassLoader.getSystemClassLoader()).loadClass("com.example.MyClass");
        Method method = classToLoad.getDeclaredMethod("run", new Class[0]);
        method.invoke(classToLoad, new Object[0]);

So, In run() method, how I can get current value of field? Thank you!

public static void run()  {
    // How?

}

Solution

  • I found the solution using getContextClassLoader

    Class clazz = callerClasses.loadClass("com.example.MainActivity");       
    Fields field = new Fields();
    Field field= clazz.getDeclaredField("field");
    flag.setAccessible(true);
    Log.d(TAG, "field: " + flag.get(field));
    

    Which "Fields" is an inner class in Dex code

    private static class Fields {
    
        private static String field = "test";
    }