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

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

问题描述

我不知道是否以及如何可以动态加载地塞米松或类文件 在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:

<一个href="http://www.google.com/$c$csearch/p?hl=en#atE6BTe41-M/vm/Jni.c&q=Jni.c">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.

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

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