如何在 android/dalvik 上动态加载 Java 类? [英] How to load a Java class dynamically on android/dalvik?

查看:46
本文介绍了如何在 android/dalvik 上动态加载 Java 类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否以及如何动态加载 dex 或 class 文件在 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:

    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(); 
            } 
    } 

而 Foo 接口是这个

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 代码,发现了这个:

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/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?

推荐答案

有一个 示例 Dalvik 测试套件中的 DexClassLoader.它反射性地访问类加载器,但如果您针对 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 的条目.您可以使用 SDK 附带的 dx 工具创建这样的 jar.

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.

这篇关于如何在 android/dalvik 上动态加载 Java 类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆