Deepu--Java
Deepu--Java

Reputation: 3820

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

Upvotes: 3

Views: 6603

Answers (1)

Jigar Joshi
Jigar Joshi

Reputation: 240860

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

Upvotes: 4

Related Questions