Class load from absolute path

孤人 提交于 2020-12-11 02:05:55

问题


I have a class and I want to load that class by absolute path but I am getting ClassNotFoundException. I had been through many threads like this SO and found that it's not correct to load class from absolute path.

    InputStream stream = new Check().getClass().getResourceAsStream(clazz+".class");

    OutputStream os = new FileOutputStream(new File("D:\\deep.class"));
    byte[] array = new byte[100];
    while(stream.read(array) != -1){
        os.write(array);
    }
    os.close();
    stream.close();
    Object obj = Class.forName("D:\\deep.class").newInstance();//getting exception here
    System.out.println(obj instanceof Check);

回答1:


You need to use URLClassLoader to load class in this use case

URLClassLoader urlClassLoader = URLClassLoader.newInstance(new URL[] {
       new URL(
           "file:///D:/"
       )
});

Class clazz = urlClassLoader.loadClass("deep");


来源:https://stackoverflow.com/questions/26966889/class-load-from-absolute-path

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!