01: package net.xoetrope.builder.editor.plugin;
02:
03: import java.net.URL;
04: import java.net.URLClassLoader;
05: import java.net.JarURLConnection;
06: import java.lang.reflect.Method;
07: import java.lang.reflect.Modifier;
08: import java.lang.reflect.InvocationTargetException;
09: import java.util.jar.Attributes;
10: import java.io.IOException;
11:
12: /**
13: * A class loader for loading jar files, both local and remote.
14: */
15: class JarClassLoader extends URLClassLoader {
16: private URL url;
17:
18: public static final String XUI_PLUGIN_CLASS = "XuiEditorPlugin-Class";
19:
20: /**
21: * Creates a new JarClassLoader for the specified url.
22: *
23: * @param url the url of the jar file
24: */
25: public JarClassLoader(URL url) {
26: super (new URL[] { url });
27: this .url = url;
28: }
29:
30: /**
31: * Returns the name of the jar file main class, or null if
32: * no "Main-Class" manifest attributes was defined.
33: */
34: public String getMainClassName() throws IOException {
35: URL u = new URL("jar", "", url + "!/");
36: JarURLConnection uc = (JarURLConnection) u.openConnection();
37: Attributes attr = uc.getMainAttributes();
38: return attr != null ? attr.getValue(XUI_PLUGIN_CLASS) : null;
39: }
40:
41: /**
42: * Invokes the application in this jar file given the name of the
43: * main class and an array of arguments. The class must define a
44: * static method "main" which takes an array of String arguemtns
45: * and is of return type "void".
46: *
47: * @param name the name of the main class
48: * @param args the arguments for the application
49: * @exception ClassNotFoundException if the specified class could not
50: * be found
51: * @exception NoSuchMethodException if the specified class does not
52: * contain a "main" method
53: * @exception InvocationTargetException if the application raised an
54: * exception
55: */
56: public void invokeClass(String name, String[] args)
57: throws ClassNotFoundException, NoSuchMethodException,
58: InvocationTargetException {
59: Class c = loadClass(name);
60: Method m = c.getMethod("main", new Class[] { args.getClass() });
61: m.setAccessible(true);
62: int mods = m.getModifiers();
63: if (m.getReturnType() != void.class || !Modifier.isStatic(mods)
64: || !Modifier.isPublic(mods)) {
65: throw new NoSuchMethodException("main");
66: }
67: try {
68: m.invoke(null, new Object[] { args });
69: } catch (IllegalAccessException e) {
70: // This should not happen, as we have disabled access checks
71: }
72: }
73:
74: }
|