This week's book giveaway is in the
Agile and other Processes
forum.
We're giving away four copies of
The Mikado Method
and have Ola Ellnestam and Daniel Brolund on-line!
See
this thread
for details.
A friendly place for programming greenhorns!
Big Moose Saloon
Search
|
Java FAQ
|
Recent Topics
Register / Login
Win a copy of
The Mikado Method
this week in the
Agile and other Processes
forum!
JavaRanch
»
Java Forums
»
Java
»
Java in General
Author
dynamically loading a class file from a jar file
Srinivas Ramgopal
Ranch Hand
Joined: Aug 06, 2006
Posts: 63
posted
Jul 30, 2007 18:24:00
0
Hi all,
I wrote a
java
program to load a .class file from a jar file.
The .class file resides in a different namespace than that of this java program.
I am using Class.forName(fully qualified class name) which is throwing a
java.lang.ClassNotFoundException
exception during runtime.
Code is as follows:
JarFile jarFile = new JarFile("../lib/xyz.jar"); JarEntry entry = jarFile.getJarEntry("zz/xx/Foo.class"); InputStream input = jarFile.getInputStream(entry); InputStreamReader isr = new InputStreamReader(input); BufferedReader reader = new BufferedReader(isr); String className = entry.getName(); Class clazz= Class.forName("className"); clazz.newInstance();
Any input is highly appreciated.
Thanks in advance.
Freddy Wong
Ranch Hand
Joined: Sep 11, 2006
Posts: 959
I like...
posted
Jul 30, 2007 20:06:00
0
I don't think that's how to dynamically load a JAR. Try to use
URLClassLoader
.
File jarFile = new File("/home/freddy/jars/HelloWorld.jar"); String className = "helloworld.Main"; try { URL fileURL = jarFile.toURI().toURL(); String jarURL = "jar:" + fileURL + "!/"; URL urls [] = { new URL(jarURL) }; URLClassLoader ucl = new URLClassLoader(urls); Messenger m = (Messenger) Class.forName(className, true, ucl).newInstance(); System.out.println(m.getMessage()); } catch (MalformedURLException ex) { ex.printStackTrace(); } catch (InstantiationException ex) { ex.printStackTrace(); } catch (IllegalAccessException ex) { ex.printStackTrace(); } catch (ClassNotFoundException ex) { ex.printStackTrace(); }
SCJP 5.0, SCWCD 1.4, SCBCD 1.3, SCDJWS 1.4
My Blog
Bert Bates
author
Sheriff
Joined: Oct 14, 2002
Posts: 8712
posted
Aug 01, 2007 07:37:00
0
off to the intermediate forum
Eliminate fossil fuel subsidies. (If you're not on the edge, you're taking up too much room.)
I agree. Here's the link:
http://zeroturnaround.com/jrebel
- it saves me about five hours per week
subject: dynamically loading a class file from a jar file
Similar Threads
input from console
Stream classes
readUTF not working
images in jar file
about Readline()
All times are in JavaRanch time: GMT-6 in summer, GMT-7 in winter