如何在Android / Dalvik的动态加载的Java类?加载、动态、如何在、Dalvik

由网友(都一样)分享简介:我不知道是否以及如何可以动态加载地塞米松或类文件在Dalvik的,一些quick'n'dirty测试功能我写的是这样的:I'm wondering if and how one can load dex or class files dynamically in dalvik, some quick'n'dirt...

我不知道是否以及如何可以动态加载地塞米松或类文件 在Dalvik的,一些quick'n'dirty测试功能我写的是这样的:

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:

    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

    public interface Foo { 
            int get42(); 
    } 

和f.dex包含一些dx'ed实现该接口的:

and f.dex contains some dx'ed implementation of that interface:

    public class FooImpl implements Foo { 
            public int get42() { 
                    return 42; 
            } 
    } 

上面的测试车手在抛出的defineClass(),它不 工作,我调查了Dalvik的code和发现这一点:

The above test driver throws at defineClass() and it doesn't work and I investigated the dalvik code and found this:

http://www.google.com/$c$csearch/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?

推荐答案

有一个的例如 DexClassLoader在Dalvik的测试套件。它访问的类加载器反思,但如果你正在构建针对Android SDK中你可以这样做:

There's an example of DexClassLoader in the Dalvik test suite. It accesses the classloader reflectively, but if you're building against the Android SDK you can just do this:

String jarFile = "path/to/jarfile.jar";
DexClassLoader classLoader = new DexClassLoader(
    jarFile, "/tmp", null, getClass().getClassLoader());
Class<?> myClass = classLoader.loadClass("MyClass");

对于这项工作,jar文件应包含一个名为条目 classes.dex 。您可以创建一个 DX 工具这样的罐子附带的SDK。

For this to work, the jar file should contain an entry named classes.dex. You can create such a jar with the dx tool that ships with your SDK.

阅读全文

相关推荐

最新文章