Loading Java objects using refelection throws a ClassNotFoundException with a superclass

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!

+4
source share
1 answer

There may be other classes in the JAR that need a custom subclass, but you select only one class file.

For example, let's say someone creates AbstractCustomRod , and then MyCustomRod , which extends it and puts them in a JAR file? Your code skips AbstractCustomRod , and MyCustomRod cannot be loaded.

If you want to indicate that inheritance cannot be inheritance except Rod, and not auxiliary classes in the JAR file, then the only meaning of JARs add is that they can be signed - if you don’t care, you can also get simple files .class, which guarantee it exactly one class.

Depending on what you are actually doing, you may need to rethink this general design - these kinds of things are very fragile for changes in parent classes, and depending on where these custom subclasses come from, it would be very easy to complete the malicious code .

0
source

Source: https://habr.com/ru/post/1502331/


All Articles