ManMohan
ManMohan

Reputation: 193

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

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

Upvotes: 0

Views: 457

Answers (2)

Nirmal
Nirmal

Reputation: 4829

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

Upvotes: 3

Andreas Dolk
Andreas Dolk

Reputation: 114767

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.

Upvotes: 8

Related Questions