I am working with Swing in Net Beans. I have my own jar which contains classes and methods inside it. I will call those classes and methods using JAVA Reflection API but before that I want to load my Jar into class path at run time. I have a J Button and on click of that I am getting Jar Name and Jar path. But I am failing to load Jar to classpath at run time. Got some links but were not helpful. Please provide me with simple example. I should load my jar to classpath. That's the only problem for me.I will take care of that. Please help.
Asked
Active
Viewed 1,158 times
-1
-
You need to use a `Classloader` of some kind, take a look at [`URLClassloader`](http://docs.oracle.com/javase/7/docs/api/java/net/URLClassLoader.html). Just remember, when you want to load these classes, you're going to need to use this classloader to do it, it won't be available through the default class loading mechanisms you've been use to. – MadProgrammer Feb 12 '15 at 05:41
1 Answers
3
You can load classes at run time through the use of a ClassLoader
, take a look at URLClassLoader
for example
File yourJarFile = ...;
URLClassLoader classLoader = new URLClassLoader(new URL[]{yourJarFile.toURI().toURL()});
This will then allow you to load classes and instantiate them...
Class class = classLoader.loadClass("fully.qualified.packagename.to.your.AwesomeClass");
You can then instantiate them using something like...
Object obj = class.newInstance();
Or reflection if you want to use a specific constructor. Just remember, you won't be able to reference these classes directly within the current class loader context, as the current class loader knows nothing about them

MadProgrammer
- 343,457
- 22
- 230
- 366
-
Amazing one...... Working Excellent....Thank U so much for your wonderful answer... but in 'Class class = classLoader.loadClass("fully.qualified.packagename.to.your.AwesomeClass");' we have to give the class name manually.... but wanted to load this class at runtime manually and i got solution for that also using this code 'JarFile jarFile = new JarFile(myJarFile.getAbsoluteFile()); Enumeration allEntries = jarFile.entries(); while (allEntries.hasMoreElements()) { JarEntry entry = (JarEntry) allEntries.nextElement(); ' – Sreepad Chitragar Feb 13 '15 at 08:01
-
It depends on what you're trying to do. When I do this, I'm usually doing some kind of plugin, so I a create text/xml which I can use getResource and configure the entry class that I want to load to get started – MadProgrammer Feb 13 '15 at 08:57