I'm attempting to use reflection to load a custom object (Rod
) from a jar file. I have managed to get it to find the jar file and scan the class for the needed annotation, but whenever I call classLoader.loadClass()
I get a ClassNotFoundException
for the class that the class I'm attempting to load extends.
This is the code for the ClassLoader:
public static Set<Rod> getRods(File rodDirectory) throws Exception {
rodDirectory.mkdir();
URLClassLoader classLoader;
Set<Rod> rods = new HashSet<Rod>();
for (File f : rodDirectory.listFiles()) {
if (f.isDirectory() || !f.getName().endsWith(".jar"))
continue;
JarFile jar = new JarFile(f);
Enumeration<JarEntry> e = jar.entries();
classLoader = URLClassLoader.newInstance(new URL[]{new URL("jar:file:" + f.getAbsolutePath() + "!/")});
while (e.hasMoreElements()) {
JarEntry j = (JarEntry) e.nextElement();
if(j.isDirectory() || !j.getName().endsWith(".class")){
continue;
}
Class<?> c = classLoader.loadClass(j.getName().substring(0, j.getName().length() - 6));
CustomRod a = c.getAnnotation(CustomRod.class);
if (a == null)
continue;
if (a.minimumVersion() < RodsTwo.getVersion())
continue;
rods.add((Rod) c.getConstructor().newInstance());
}
jar.close();
}
return rods;
}
This is the code inside the jar I'm attempting to load:
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.Player;
import ca.kanoa.RodsTwo.Objects.ConfigOptions;
import ca.kanoa.RodsTwo.Objects.CustomRod;
import ca.kanoa.RodsTwo.Objects.Rod;
@CustomRod(minimumVersion=1.001)
public class Test extends Rod {
public Test() throws Exception {
super("Test", 1, 46, new ConfigOptions(), 200);
}
@Override
public boolean run(Player arg0, ConfigurationSection arg1) {
arg0.sendMessage("HI!");
return true;
}
}
And all my other code can by found here.
I've just started playing around with reflection and any help with be awesome!