Android - 在运行时加载外部.jar

时间:2015-11-28 09:46:23

标签: java android urlclassloader

我想在运行时加载外部库。

以下是来源:

import java.lang.*;
import java.net.*;
import java.io.*;

public class Main {
    public static void main (String args[]) throws Exception {
        System.out.println("Load support library");
        File file = new File("/sdcard/lib/android-support-v4.jar");
        URL url = file.toURI().toURL();
        URL[] urls = {url};
        URLClassLoader cl = new URLClassLoader(urls);
        Class clazz = cl.loadClass("android.support.v4.view.ViewCompat");
    }
}

此库是Google的支持库。 它位于“/sdcard/lib/android-support-v4.jar”。

我想得到“android.support.v4.view.ViewCompat”类,但是源总是抛出ClassNotFoundException。

1 个答案:

答案 0 :(得分:0)

JCL class loader framework怎么样? 用法示例:

JarClassLoader jcl = new JarClassLoader();  
jcl.add("myjar.jar"); //Load jar file  
jcl.add(new URL("http://myserver.com/myjar.jar")); //Load jar from a URL  
jcl.add(new FileInputStream("myotherjar.jar")); //Load jar file from stream  
jcl.add("myclassfolder/"); //Load class folder  
jcl.add("myjarlib/"); //Recursively load all jar files in the folder/sub-folder(s)  

JclObjectFactory factory = JclObjectFactory.getInstance();  

//Create object of loaded class  
Object obj = factory.create(jcl,"mypackage.MyClass");