Slager .
Posts: 16
Nickname: slager
Registered: May, 2003
|
|
Re: plug ins
|
Posted: Nov 21, 2005 2:02 AM
|
|
Hi,
This should get you going. It's a classloader loading a specific jar (you would extend it by listing the plugin directory for jar files)
Each jarfile is examined for .class files and classes are loaded to see which interfaces they implement. Note that you may want to check recursively for each interface found because an interface may be extending your plugin interface.
Of course you can also try using instanceof (since the interface class is definately loadable in your case)
Anyway loads of options ;) Good luck.
import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.util.Enumeration; import java.util.LinkedList; import java.util.List; import java.util.jar.JarFile; import java.util.zip.ZipEntry;
public class CheckJar {
public static class MyClassLoader extends URLClassLoader { private File jarFile; public MyClassLoader(String _sJar) throws MalformedURLException { super(new URL[0]); jarFile = new File(_sJar); addURL(jarFile.toURL()); } public List findClasses(String ifName) throws IOException, ClassNotFoundException { List classList = new LinkedList(); JarFile jf = new JarFile(jarFile); Enumeration e = jf.entries(); while(e.hasMoreElements()) { ZipEntry z = (ZipEntry)e.nextElement(); if(z.getName().endsWith(".class")) { String className = z.getName().replace('\\', '.').replace('/','.'); try { // load the class (problably needs catching because dependencies may be unresolvable Class c = loadClass(className.substring(0, className.length() - ".class".length())); Class interfaces[] = c.getInterfaces(); for(int i = 0 ; i < interfaces.length; i++) { // you may want to do this recursively (in case interfaces were extended) if(interfaces[i].getName().equals(ifName)) { // jay we got a plugin System.out.println("Usable class : " + className); classList.add(className); } } } catch(Throwable t) { System.out.println("problem with : " + className); } } } return classList; } } public static void main(String[] args) throws Exception { MyClassLoader cl = new MyClassLoader(args[0]); Thread.currentThread().setContextClassLoader( cl ); List classList = cl.findClasses(args[1]); } }
|
|