I'm trying to load a .jar file into my project dinamically: my programme has to look in a directory in my pc and load the code inside all the jar files as it was part of the project since the beginning.
I need to be able to call method from that class, and also if in my project I have the class Bee and in the jar file I have the class QueenBee extends Bee it has to work without the class Bee in the jar file.
I tried using URLClassLoader:
String homeDir = System.getProperty("user.home");
String modsPath = homeDir + File.separator + "AppData" + File.separator + "Roaming" + File.separator + ".minecraft" + File.separator + "mods";
File modsFolder = new File(modsPath);
if(modsFolder.exists() && modsFolder.isDirectory()){
for (File file : Objects.requireNonNull(modsFolder.listFiles())){
if(!getFileExtension(file).equals("jar")){
continue;
}
// Load the class from the JAR file.
URLClassLoader classLoader = new URLClassLoader(new URL[]{file.toURI().toURL()});
Class<?> modClass;
try{
modClass = classLoader.loadClass("mymod.MyMod");
modClass.getDeclaredMethod("scanMods").invoke(modClass);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
The jar file is:
file.jar
|_ _ mymod (folder)
|_ _ MyMod.java
But I get java.lang.ClassNotFoundException: mymod.MyMod
I probably need something different than URLClassLoader?