33

dalvikでdexまたはクラスファイルを動的にロードできるかどうか、またどのようにロードできるか疑問に思っています。私が書いたクイックアンドダーティテスト関数は次のとおりです。

    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インターフェースはこれです

    public interface Foo { 
            int get42(); 
    } 

f.dex には、そのインターフェースの dx 化された実装が含まれています。

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

上記のテスト ドライバーは defineClass() をスローしますが、機能しません。dalvik コードを調査したところ、次のことがわかりました。

http://www.google.com/codesearch/p?hl=en#atE6BTe41-M/vm/Jni.c&q=Jni.c ...

だから、これが他の方法で可能かどうか、または不可能であると思われるかどうか、誰かが私を啓発できるかどうか疑問に思っています。それが不可能な場合、誰かがこれが不可能な理由を提供できますか?

4

1 に答える 1

51

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");

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.

于 2010-06-11T15:55:03.377 に答える