Just wondering is there any way to modify Classpath in your program and force them to include a new directory in classpath ??

peter_budo commented: Weak problem description, we do not like second guess -4

Try this..

We can set class path from command prompt also..

Runtime r=Runtime.getRuntime();
r.exec("set classpath=your desired path");

Not sure you can change it once the JVM has started.
Try it and see what happens.
You may need to build your own classloader that uses the paths you want it to use.

Not easily. Not directly. Runtime.getRuntime().exec("set CLASSPATH=your desired path"); is not portable and while it sets the CLASSPATH environment variable in the child process, the child process immediately exits. You could set the CLASSPATH and run a program this way, but it's not portable. System.setProperty("java.class.path", System.getProperty("java.class.path") + File.pathSeparator + "/my/path"); does not work because the system class loaders don't fetch the updated property.

That pretty much leaves us with extending or hacking a ClassLoader. Google can help. Here are some promising threads:

http://stackoverflow.com/questions/1010919/adding-files-to-java-classpath-at-runtime

http://stackoverflow.com/questions/252893/how-do-you-change-the-classpath-within-java

http://www.velocityreviews.com/forums/t129750-changing-the-classpath-at-runtime.html

Thanks guys for showing some lines. I agree with jeff though that once JVM started will System classloader will able to pick the new Classpath , indeed custom Classloader can be a solution and I am going to try that. Thanks for those links quite helpful.

When using class loaders, if the system says that you cannot cast class X to class X because they're incompatible (with "X" and "X" being the exact same fully qualified class name with path) -- you're not losing your mind; you have class loader problems.

Knowing this can save you days of grief. But don't worry; you've already signed up for plenty of days of grief by deciding to play with class loaders. There will be plenty to go around! ;->

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.