Loading a class from an absolute path

I have a class and I want to load this class on an absolute path, but I am getting a ClassNotFoundException. I went through many threads like this SO and found it was not correct to load a class from an 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);

      

+3


source to share


1 answer


You need to use URLClassLoader

to load the class in this use case



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

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

      

+2


source







All Articles