开发者

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 ma开发者_StackOverflow中文版nually ?


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.


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜