I am developing a class loader that will load plugins into my software. I have a jar file with two things in it, the package containing my code, and a text file containing the name of the class that I want to load from the jar. Is there a way for my app to read the text in the file and get the class name, then load the class with that name from the jar file?
Asked
Active
Viewed 72 times
0
-
I think you just have to write it. What is your problem ? Your entry point will be a class that reads the text file, loads the classes and then does whatever you want – Dici Jan 04 '15 at 20:05
-
I think that this [answer][1] should suffice. It is that easy. [1]: http://stackoverflow.com/questions/9819318/create-new-classloader-to-reload-class – Alessandro Santini Jan 04 '15 at 20:06
1 Answers
0
This is the code that works:
content = new Scanner(new File("plugins/" + listOfFiles[i].getName().replaceAll(".jar", "") + "/" + "plugin.cfg")).useDelimiter("\\Z").next();
URL[] urls = null;
try {
File dir = new File("plugins/" + listOfFiles[i].getName());
URL url = dir.toURL();
urls = new URL[]{url};
} catch (MalformedURLException e) {
}
try {
ClassLoader cl = new URLClassLoader(urls);
Class cls = cl.loadClass(content.replaceAll("Main-Class:", ""));
Method enable = cls.getMethod("enable", (Class<?>[]) null);
enable.invoke(enable, null);
}catch (Exception e) {
System.out.println("One of the installed plugins might have an invalid plugin.cfg.");
}
The code reads a file with the name of the main class in it, and then loads that class from the jar file it extracted earlier.

Noodly_Doodly
- 69
- 2
- 11