无法加载类路径中不存在的类

时间:2018-12-23 01:52:19

标签: java classpath classloader classnotfoundexception

我尝试加载类路径中不存在的类。我要加载的类在默认程序包中。当我编译项目时,请采取ClassNotFoundException。

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

public class PathClassLoaderImpl extends ClassLoader implements PathClassLoader {
    private String path = null;

    @Override
    public void setPath(String dir) {
        path = dir;
    }

    @Override
    public String getPath() {
        return path;
    }

    @Override
    public Class<?> loadClass(String name) {
        try {
            URL dirUrl = new URL(path);
            URLClassLoader cl = new URLClassLoader(new URL[] {dirUrl},
                    getClass().getClassLoader());
            Class loadedClass = cl.loadClass(name);
            return  loadedClass;
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

}

import java.lang.reflect.Method;

public class Main {

    public static void main(String[] args) {
        PathClassLoaderImpl example = new PathClassLoaderImpl();
        example.setPath("file:\\D:\\Projects JAVA\\Reflection\\out\\production\\Reflection");
        Method[] methods = example.loadClass("Factory.class").getMethods();
        for (Method m : methods) {
            System.out.println(m.toString());
        }

    }
}

0 个答案:

没有答案