我想在我的应用程序中使用 dex 类加载器,我在那里阅读了 developer.google 指南和一些关于它的问题,但我仍然无法找到如何使用 dex 类加载器。如果有人在这里解释一个例子,我真的很感激。谢谢你。
我的代码:此代码不起作用
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loadDexClassses("dex-" + getApplicationContext().getPackageName().hashCode());
}
public static void loadDexClassses(String optDexFolder) {
if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
Log.v("loadDexClassses", "LoadDexClasses is only available for ICS or up");
}
File[] files = new File("data/local/tmp/testjars/").listFiles();
if (files == null) {
Log.v("loadDexClasses", "There was no " + "data/local/tmp/testjars/");
return;
}
Log.v("loadDexClasses", "Dex Preparing to loadDexClasses!");
for (File file : files) {
Log.v("loadDexClasses", "In for!");
final File tmpDir = new File("data/local/tmp/optdexjars/" + optDexFolder + "/");
tmpDir.mkdir();
final DexClassLoader classloader = new DexClassLoader(
file.getAbsolutePath(), tmpDir.getAbsolutePath(),
"data/local/tmp/natives/",
ClassLoader.getSystemClassLoader());
Log.v("loadDexClasses", "Searching for class : "
+ "com.registry.Registry");
Class<?> classToLoad = null;
try {
classToLoad = (Class<?>) classloader
.loadClass("com.registry.Registry");
Field classesField = classToLoad.getDeclaredField("_classes");
ArrayList<Class<?>> classes = (ArrayList<Class<?>>) classesField.get(null);
for(Class<?> cls : classes) {
Log.v("loadDexClasses", "Class loaded " + cls.getName());
}
for (Class<?> cls : classes) {
Log.v("loadDexClasses", "Class loaded " + cls.getName());
if (cls.getName().contains("ClassToBeImported")) {
Method m = cls.getMethod("method");
ClassLoader xb = (ClassLoader) m.invoke(null);
if (xb.equals(ClassLoader.getSystemClassLoader()))
Log.v("loadDexClasses", "Same ClassLoader");
else
Log.v("loadDexClasses", "Different ClassLoader");
}
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
}