Friday, 9 August 2013

Java - URLClassLoader invoke a method

Java - URLClassLoader invoke a method

Can you guys help me understand everything about invoking methods for
URLClassLoader?
I spent couple of hours searching the web about concrete example how it
works. None of those were clear step by step explanations. I managed to
call a class but I can't figure out the methods and parameters. Can
someone guide me through?
The class I want to load (just a generic class to see how it works):
class SwitchClass {
public void callSwitch (String arg) {
switch (arg) {
case "website":
System.out.println("Switch case for website string");
break;
case "url":
System.out.println("Switch case for url string");
break;
default:
break;
}
}
}
Example I tried to load, understand and adjust:
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
public class MainClass {
static public void main(String args[]) throws Exception {
URL myurl[] = { new URL("file:///C:/CH3/ClassLoader/web/"),
new URL("http://www.java2s.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);
}
}
Thank you in advance!

No comments:

Post a Comment