• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to load jar dynamically???

 
Ram Dhan Yadav K
Ranch Hand
Posts: 321
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Matt Senecal
Ranch Hand
Posts: 255
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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).]
 
Ram Dhan Yadav K
Ranch Hand
Posts: 321
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Matt Senecal
Ranch Hand
Posts: 255
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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).]
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic