не могу загрузить класс, не представленный в пути к классам - PullRequest
0 голосов
/ 23 декабря 2018

Я пытаюсь загрузить класс, не представленный в пути к классам.Класс, который я хочу загрузить, находится в пакете по умолчанию.Когда я компилирую проект, беру 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());
        }

    }
}
...