JAVA动态加载JAR

// 生成JAR包D:\TestClass.jar

package hand.java.loadjar;

public class TestClass {

    private String sayHello = "Hello World!!";

    public String sayHello() {
        return this.sayHello;
    }
}

// 创建一个测试类

package hand.java.loadjar;

import java.net.URL;
import java.net.URLClassLoader;
import java.lang.reflect.Method;

public class LoadJarTest {    
    public LoadJarTest(){
        try {
            URL url = new URL("file:D:\\TestClass.jar");  
            URLClassLoader  loader = new URLClassLoader(new URL[]{ url });   
            // Load class
            Class<?> myclass = loader.loadClass("hand.java.loadjar.TestClass");
            // Gene new object
            Object myobject = myclass.newInstance();   
            // Get function
            Method method = myclass.getDeclaredMethod("sayHello");
            // Make the function  valid
            method.setAccessible(true);
            // Invoke method
            System.out.println(method.invoke(myobject));   
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    @SuppressWarnings("unused")
    public static void main(String[] args){
        LoadJarTest loadjar = new LoadJarTest();
    }
}

运行,输出内容:

Hello World!!

 


 


 


package hand.dynamic.jar;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;

public class JarLoadUtil {

    private static String jar_path = "D:\\JAR";
    private static URLClassLoader loader = null;
    // private static String curDir = System.getProperty("user.dir");
    private static String separator = System.getProperty("file.separator");

    public static URLClassLoader getURLClassLoader() {
        if (loader == null) {
            String fileNames[] = new File(jar_path).list();
            if (fileNames != null && fileNames.length > 0) {
                URL urls[] = new URL[fileNames.length];
                for (int i = 0; i < fileNames.length; i++) {
                    try {
                        // if (fileNames[i].equals("dom4j-1.6.1.jar"))
                        urls[i] = new URL(jar_path + separator + fileNames[i]);
                    } catch (MalformedURLException e) {
                        System.out.println("加载指定目录下JAR文件出错!");
                        throw new RuntimeException("加载指定目录下JAR文件出错!", e);
                    }
                }
                loader = new URLClassLoader(urls);
            }
        }

        return loader;
    }
}

posted @ 2014-04-21 14:53  新新向荣  阅读(756)  评论(0编辑  收藏  举报