本文介绍了来自绝对路径的类加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类,并且我想通过绝对路径加载该类,但是我正在收到ClassNotFoundException.我经历过很多这样的线程,发现从绝对路径加载类是不正确的.

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);

推荐答案

您需要使用 URLClassLoader 以便在此用例中加载类

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");

这篇关于来自绝对路径的类加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-12 07:52