0

How we can set the class path with the help our java code and not manually ?

ManMohan
  • 193
  • 1
  • 3
  • 13
  • 2
    Please explain what you're trying to achieve. – Joachim Sauer Sep 12 '11 at 06:34
  • hi Joachim Sauer, Firstly heartly thanks to take interest in my question.Actually its the question asked from me in an interview. The question is same that "how you can set the class path with the help of the java code ?" not through the environmental veriable. – ManMohan Sep 13 '11 at 08:58

2 Answers2

8

We can't. The classpath has to be set at startup time of the java virtual machine. We can't change it from a running application.

It is possible to load classes from locations and jar files that are not on the classpath. Either use the URLClassloader to load a single class from a known (File-)URL or implement your own classloader for more magic.

Community
  • 1
  • 1
Andreas Dolk
  • 113,398
  • 19
  • 180
  • 268
3

If you want to edit the classpath for loading the jar files from the path other then the classpath then following code using URLClassLoader (as @Andreas_D suggested) may be helpful to you :

import java.io.IOException;
import java.io.File;
import java.net.URLClassLoader;
import java.net.URL;
import java.lang.reflect.Method;

public class ClassPathHacker {

private static final Class[] parameters = new Class[]{URL.class};

public static void addFile(String s) throws IOException {
   File f = new File(s);
   addFile(f);
}//end method

public static void addFile(File f) throws IOException {
   addURL(f.toURL());
}//end method


public static void addURL(URL u) throws IOException {

  URLClassLoader sysloader = (URLClassLoader) ClassLoader.getSystemClassLoader();
  Class sysclass = URLClassLoader.class;

  try {
     Method method = sysclass.getDeclaredMethod("addURL", parameters);
     method.setAccessible(true);
     method.invoke(sysloader, new Object[]{u});
  } catch (Throwable t) {
     t.printStackTrace();
     throw new IOException("Error, could not add URL to system classloader");
  }//end try catch

   }//end method

}//end class
Nirmal
  • 4,789
  • 13
  • 72
  • 114