Search code examples
javaclassloader

Class load from absolute path


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

Solution

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