Hi All, I have a jar file at a location and i have to load it dyanmically, read its contents, load a class in it, invoke methods on that loaded class. I know the location of this jar file at runtime, and so apparently the location is not in the classpath. How do i accomplish this whole task? Java gurus, any idea/code/references etc. thanks, Ram Dhan YK
Ram Dhan Yadav (SCJP, SCWCD, SCJA-I, IBM EC(483))
"We are what we repeatedly do. Excellence, then, is not an act, but a habit."
Since you know the location of the jar you can use a URLClassLoader. You first need to format the location of the JAR as a URL. For example, if the jar is in c:/temp/Matt/HelloWorld.jar, the URL would look like this: jar:file:/C:/temp/Matt/HelloWorld.jar!/ Then create the URL and the classloader associated with it.
Then load the class you need. Let's say we're loading "HelloWorld":
You next need to extract the method you need to run and invoke it. For this example, let's assume that we're invoking "main". The getMethod and invoke methods require arrays as one of their parameters. getMethod requires a Class array that identifies the method's formal parameter types. For example, the parameter to main is an array of strings, so the class array we would need to pass into getMethod would be an array containing the class type of an array of Strings (feel dizzy yet?). The parameter array is an array of Objects that contains the actual objects being passed into the method being envoked. In this case, we'll say "main" requires one String.
Not you can get the method from the Jar and invoke it:
Let me know if anything needs to be clarified. [This message has been edited by Matt Senecal (edited October 05, 2001).]
There's nothing more dangerous than a resourceful idiot. ---Dilbert
Ram Dhan Yadav K
Joined: Aug 13, 2001
Thaks Matt, I will work on this and let you know. Well one more querry. Does this work in weblogic environment. I am suppossed to use this in a servlet. Thanks, Ram Dhan YK
Joined: Dec 01, 2000
I'm not sure about the weblogic environment. I've only used this method in a standalone desktop situation, and it worked well.
[This message has been edited by Matt Senecal (edited October 05, 2001).]