java 加载指定目录下的jar包(自定义ClassLoader)

自定义的class,打成jar包放在/opt

package com.laomei.test;

public class HelloWorld {

    public void hello() {
        System.out.println("hello");
    }
}

构造自定义URLClassLoader

public class MyClassLoader extends URLClassLoader {

    public MyClassLoader(final String path, final ClassLoader parent) throws MalformedURLException {
        super(new URL[]{ new URL(path) }, parent);
    }
}

加载HelloWorld

public class ClassLoaderTest {
    public static void main(String[] args) throws MalformedURLException {
        try {
            Class.forName("com.laomei.test.HelloWorld");
        } catch (ClassNotFoundException e) {
            System.out.println("class HelloWorld is not found");
        }
        String path = "jar:file:///opt/classloader-test.jar!/";
        MyClassLoader myClassLoader = new MyClassLoader(path, Thread.currentThread().getContextClassLoader().getParent());
        Thread.currentThread().setContextClassLoader(myClassLoader);
        try {
            Class clazz = Thread.currentThread()
                    .getContextClassLoader()
                    .loadClass("com.qunhe.test.HelloWorld");
            Object obj = clazz.newInstance();
            Method hello = clazz.getMethod("hello", null);
            hello.invoke(obj, null);
        } catch (ClassNotFoundException e) {
            System.out.println("class HelloWorld is not found");
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}

结果

class HelloWorld is not found
hello

你可能感兴趣的:(【Java】,【ClassLoader】)