| Author |
How to set the classpath through a java program ?
|
Vibhas Zanpure
Greenhorn
Joined: May 05, 2010
Posts: 2
|
|
Is there any proper way to do it ? In my engineering project, I am actually uploading .jar files or directories(which contain .class files).... After uploading a particular .jar/.class file from a directory path different than the original classpath, how do i invoke Reflection on it ?
My questions are ::
1) How to set classpath for a project/jar which we upload from a different directory at run time ?
2) Is there a way to invoke reflection of a .jar file just like we do it on a single .class file ?
Thanks
|
 |
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32839
|
|
Welcome to the Ranch
This part of the Java™ Tutorials tells you about jar files; you can add a classpath to a jar file, which the link describes.
|
 |
Rob Spoor
Sheriff
Joined: Oct 27, 2005
Posts: 19232
|
|
|
If the classes in the JAR file need to be dynamically loaded you should use a URLClassLoader. You can use file.toURI().toURL() for getting a URL from a File instance.
|
SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions How To Answer Questions
|
 |
Vibhas Zanpure
Greenhorn
Joined: May 05, 2010
Posts: 2
|
|
@ ROB PRIME
I tried using that trick, but its not working. Thanks
Is there any way to set the class path of JVM through a program while you upload a .class file dynamically by selecting a .class file through a FileDialog.... ??
In my project, if I upload any .class file at runtime, a ClassNotFoundException is thrown by JRE if the class doesnt exist in the default classpath( i.e. the project folder)...
So how to fix this ???
Please help me, thanks.
|
 |
Gopi Chella
Ranch Hand
Joined: Apr 26, 2010
Posts: 53
|
|
@ Vibhas
Like Rob said you should use URLClassLoader class and the method file.toURL(), Since the method is protected you need to use reflection to invoke it.
The reflection is necessary to access the protected method addURL.
|
SCJP 1.5
|
 |
Rob Spoor
Sheriff
Joined: Oct 27, 2005
Posts: 19232
|
|
You can also subclass it to make the method public. Something like this:
|
 |
 |
|
|
subject: How to set the classpath through a java program ?
|
|
|