I am trying to use reflection to load a custom object ( Rod
) from a jar file. I managed to find the jar file and check the class for the required annotation, but whenever I call classLoader.loadClass()
, I get a ClassNotFoundException
for the class that the class I'm trying to load extends.
This is the code for 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 trying 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 find here .
I just started playing with reflection, and any help was awesome!
source share