What would be a good way to dynamically load java class files so that a program compiled into a jar can read all the class files in a directory and use them, and how can one write the files so that they have the necessary package name in relation to the jar?
Asked
Active
Viewed 8.4k times
3 Answers
110
I believe it's a ClassLoader
you're after.
I suggest you start by looking at the example below which loads class files that are not on the class path.
// Create a File object on the root of the directory containing the class file
File file = new File("c:\\myclasses\\");
try {
// Convert File to a URL
URL url = file.toURI().toURL(); // file:/c:/myclasses/
URL[] urls = new URL[]{url};
// Create a new class loader with the directory
ClassLoader cl = new URLClassLoader(urls);
// Load in the class; MyClass.class should be located in
// the directory file:/c:/myclasses/com/mycompany
Class cls = cl.loadClass("com.mycompany.MyClass");
} catch (MalformedURLException e) {
} catch (ClassNotFoundException e) {
}
-
Yes, I believe ClassLoader is what I'm looking for. However, can you think of a way to effectively use the loaded class? I could make it implement an interface...but how could I reference that interface? Hmm... perhaps if I were to add the compiled jar as an external jar... in that case, what should I call the package of the loaded class? If I have: /thing/myjar.jar and thing/loadedclasses/class.class, what would the declared package be for that class? – MirroredFate Jun 02 '11 at 20:36
-
Yes, you would have to agree on some interface or abstract class which the to-be-loaded classes implements / extends. (Or completely rely on reflection for the loaded classes.) – aioobe Jun 02 '11 at 20:50
-
You could use whatever package you want for your dynamic class. (It should not be named `class`, though.) Implementing a known interface is a good idea, otherwise you either have to use Reflection or other generated classes to access its methods. – Paŭlo Ebermann Jun 02 '11 at 20:51
-
Just a caveat, but you should `.close()` your `URLClassLoader` after you are done with it to prevent memory leaks. – Wolfer Sep 21 '14 at 16:15
-
Minor Fix >> use `URL url = file.toURI().toURL()` instead. `file.toURL` has been depreciated. – Irrationalkilla Dec 14 '15 at 01:10
-
Assume I do not know that the class is called `com.mycompany.MyClass`. Can I still load it? – Cardinal System Dec 07 '19 at 16:48
9
Class myclass = ClassLoader.getSystemClassLoader().loadClass("package.MyClass");
or
Class myclass = Class.forName("package.MyClass");
or loading the class from different folder which is not in the classpath:
File f = new File("C:/dir");
URL[] cp = {f.toURI().toURL()};
URLClassLoader urlcl = new URLClassLoader(cp);
Class myclass = urlcl.loadClass("package.MyClass");
For further usage of the loaded Class you can use Reflection if the loaded Class is not in your classpath and you can not import and cast it. For example if you want to call a static method with the name "main":
Method m = myclass.getMethod("main", String[].class);
String[] args = new String[0];
m.invoke(null, args); // invoke the method

d2k2
- 726
- 8
- 16
-
-
@Apostolos "MyClass" is the name of the class you want to load. its an example. – d2k2 Mar 14 '22 at 19:09
-
But how can you initialize 'obj' defined as a class that you have not imported yet, but which you want to import dynamically? This is the question here. Have you tried this code? It issues a **"cannot find symbol"** error pointing at 'MyClass' (whatever name you use for it). – Apostolos Mar 16 '22 at 09:13
-
@Apostolos It would probably require to work with an interface class. i found some example sourcecode here: https://javaranch.com/journal/200607/Plugins.html. see also this answear: https://stackoverflow.com/questions/6219829/method-to-dynamically-load-java-class-files/10067805?noredirect=1#comment7244588_6219855 some example would be nice how to use reflection to use the methods from the loaded class to fully answear the problem. – d2k2 Mar 17 '22 at 11:13
2
If you add a directory to your class path, you can add classes after the application starts and those classes can be loaded as soon as they have been written to the directory.

Peter Lawrey
- 525,659
- 79
- 751
- 1,130
-
1I noticed a problem that when classes are re-compiled into this directory once more, while application continues running, a first copy of a class continues to be in use. Java 15. – Nikolai Varankine Feb 20 '23 at 18:01