Java by API/java.net/URLClassLoader
extends URLClassLoader
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.net.JarURLConnection;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.jar.Attributes;
public class Main extends URLClassLoader {
private URL url;
public Main(URL url) {
super(new URL[] { url });
this.url = url;
}
public String getMainClassName() throws IOException {
URL u = new URL("jar", "", url + "!/");
JarURLConnection uc = (JarURLConnection) u.openConnection();
Attributes attr = uc.getMainAttributes();
return attr != null ? attr.getValue(Attributes.Name.MAIN_CLASS) : null;
}
public void invokeClass(String name, String[] args) throws ClassNotFoundException,
NoSuchMethodException, InvocationTargetException {
Class c = loadClass(name);
Method m = c.getMethod("main", new Class[] { args.getClass() });
m.setAccessible(true);
int mods = m.getModifiers();
if (m.getReturnType() != void.class || !Modifier.isStatic(mods) || !Modifier.isPublic(mods)) {
throw new NoSuchMethodException("main");
}
try {
m.invoke(null, new Object[] { args });
} catch (IllegalAccessException e) {
}
}
}
new URLClassLoader(URL[] urls)
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
public class Main {
static public void main(String args[]) throws Exception {
URL myurl[] = { new URL("file:///C:/CH3/ClassLoader/web/"),
new URL("http://www.jexp.edu/~xyx/test/") };
URLClassLoader x = new URLClassLoader(myurl);
Class c = x.loadClass("TestURL");
Class getArg1[] = { (new String[1]).getClass() };
Method m = c.getMethod("main", getArg1);
String[] my1 = { "arg1 passed", "arg2 passed" };
Object myarg1[] = { my1 };
m.invoke(null, myarg1);
Object ob = c.newInstance();
Class arg2[] = {};
Method m2 = c.getMethod("tt", arg2);
m2.invoke(ob, null);
Class arg3[] = { (new String()).getClass(), int.class };
Method m3 = c.getMethod("tt", arg3);
Object myarg2[] = { "Arg1", new Integer(100) };
m3.invoke(ob, myarg2);
}
}
URLClassLoader: getURLs()
import java.net.URL;
import java.net.URLClassLoader;
public class Main {
public static void main(String[] args) {
ClassLoader sysClassLoader = ClassLoader.getSystemClassLoader();
URL[] urls = ((URLClassLoader) sysClassLoader).getURLs();
for (int i = 0; i < urls.length; i++) {
System.out.println(urls[i].getFile());
}
}
}