Note that there are some explanatory texts on larger screens.

plurals
  1. POJava, Get all classes available to a URLClassLoader that implement a specific interface
    primarykey
    data
    text
    <p>I am working on a command line app that loads user specified text translators at runtime (path to class files/jar provided via command line arg). Basically I am taking that argument and using it to create a URLClassLoader. Then I need to find all classes available to the URLClassloader that implement the Transable interface.</p> <p>Right now I am only allowing this command line arg to be a directory with class files in it. Making the solution fairly simple (code below). But honestly I don't like the solution as it breaks down for jar files, directory of jar files, etc... Also, this obviously breaks down for any classes with a defined package, as loadClass needs the full name including the package. Anyone have a better method?</p> <pre><code> File d = new File(path); if(d.isDirectory()) { URL url = d.toURI().toURL(); ClassLoader cl = new URLClassLoader(new URL[]{url}); FilenameFilter filter = new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.endsWith(".class"); } }; for(File f : d.listFiles(filter)) { String name = f.getName().substring(0, f.getName().indexOf(".")); String key = ""; if(name.endsWith("Translator")) { key = name.substring(0, name.indexOf("Translator")); } else if(name.endsWith("translator")) { key = name.substring(0, name.indexOf("translator")); } else key = name; Class c = cl.loadClass(name); if(Transable.class.isAssignableFrom(c)) { Transable t = (Transable)c.newInstance(); env.registerTranslator(key, t); } else { System.out.println("[ClassLoader] "+c.getCanonicalName()+" will not be loaded. It is not a translator class"); } } } else { throw new Error("NOT IMPLEMENTED"); } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload