3

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);
halfer
  • 19,824
  • 17
  • 99
  • 186
Deepu--Java
  • 3,742
  • 3
  • 19
  • 30
  • `Class.forName` take as argument a fully qualified class name like `com.acme.Coyote` not a path to a class file, you will have to add `D:` to the classpath and then load the class by name –  Nov 17 '14 at 06:38
  • Yes I got you. But how can I solve this problem and Is it correct to load class from any arbitrary path? – Deepu--Java Nov 17 '14 at 06:40
  • see http://stackoverflow.com/questions/402330/is-it-possible-to-add-to-classpath-dynamically-in-java –  Nov 17 '14 at 06:40

1 Answers1

4

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");
jmj
  • 237,923
  • 42
  • 401
  • 438
  • In load class it is asking for fully qualified class name. If I am using file name "deep" then it's showing Exception in thread "main" java.lang.NoClassDefFoundError: Check – Deepu--Java Nov 17 '14 at 07:00
  • But after giving complete class name with package it is working. Can you tell why? – Deepu--Java Nov 17 '14 at 07:01
  • You just wrote class name in your question so I assumed it is just placed in default package, yes ofcourse it needs fully qualified classname, because it treats that URL as the root of the classpath while loading the class and so – jmj Nov 17 '14 at 07:03