我想在我的应用程序中使用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();
}
}
}
}
答案 0 :(得分:0)
即使三年后,我也要离开我的家。那是您的代码,但有一些改动:
DexClassLoader classloader = new DexClassLoader(
**file**, tmpDir.getAbsolutePath(),
"data/local/tmp/natives/",
ClassLoader.getSystemClassLoader());
DexClassLoader的第一个参数是dexPath-假设您在上方的该文件夹中有一些.dex文件(“ data / local / tmp / testjars /”)或jar / apk文件。