[英]How to load a Java class dynamically on android/dalvik?
I'm wondering if and how one can load dex or class files dynamically in dalvik, some quick'n'dirty test function I wrote was this: 我想知道是否以及如何在dalvik中动态加载dex或类文件,我写的一些quick'n'dirty测试函数是这样的:
public void testLoader() {
InputStream in;
int len;
byte[] data = new byte[2048];
try {
in = context.getAssets().open("f.dex");
len = in.read(data);
in.close();
DexFile d;
Class c = defineClass("net.webvm.FooImpl", data, 0, len);
Foo foo = (Foo)c.newInstance();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
whereas the Foo interface is this 而Foo界面就是这样
public interface Foo {
int get42();
}
and f.dex contains some dx'ed implementation of that interface: 和f.dex包含该接口的一些dx'ed实现:
public class FooImpl implements Foo {
public int get42() {
return 42;
}
}
The above test driver throws at defineClass() and it doesn't work and I investigated the dalvik code and found this: 上面的测试驱动程序抛出了defineClass()并且它不起作用,我调查了dalvik代码并发现了这个:
http://www.google.com/codesearch/p?hl=en#atE6BTe41-M/vm/Jni.c&q=Jni.c ... http://www.google.com/codesearch/p?hl=en#atE6BTe41-M/vm/Jni.c&q=Jni.c ...
So I'm wondering if anyone can enlighten me if this is possible in some other way or not supposed to be possible. 所以我想知道是否有人可以启发我,如果这可能以其他方式或不应该是可能的。 If it is not possible, can anyone provide reasons why this is not possible?
如果不可能,任何人都可以提供无法解释的原因吗?
There's an example of DexClassLoader in the Dalvik test suite. 在Dalvik测试套件中有一个DexClassLoader的例子 。 It accesses the classloader reflectively, but if you're building against the Android SDK you can just do this:
它反过来访问类加载器,但如果您正在构建Android SDK,则可以执行以下操作:
String jarFile = "path/to/jarfile.jar";
DexClassLoader classLoader = new DexClassLoader(
jarFile, "/tmp", null, getClass().getClassLoader());
Class<?> myClass = classLoader.loadClass("MyClass");
For this to work, the jar file should contain an entry named classes.dex
. 为此,jar文件应包含名为
classes.dex
的条目。 You can create such a jar with the dx
tool that ships with your SDK. 您可以使用SDK附带的
dx
工具创建此类jar。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.