I am trying to dynamically load from a class file. The codes below fails to invoke the methods in the class.
public static void main(String[] args) {
try {
File loadPath = new File("C:/loadtest/");
URL url = loadPath.toURI().toURL();
URL[] urls = new URL[]{url};
ClassLoader cl = new URLClassLoader(urls);
Class cls = cl.loadClass("TesterClass");
System.out.println("Classname: " + cls.getName());
Method[] m = cls.getMethods();
for (Method m1 : m){
try {
System.out.println("Method: " + m1.getName());
if (m1.getName().equals("getName")) {
Object o = m1.invoke(null, null);
System.out.println("o is : " + o);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
} catch (MalformedURLException | ClassNotFoundException e) {
}
}
The target Java class I am trying to invoke:
public class TesterClass {
public hamster() {
}
public void getName() {
System.out.println("TEST SUCCEED !!!");
}
}
What I got was:
Classname: TesterClass
Method: getName
Method: getClass
Method: hashCode
Method: equals
Aug 07, 2013 4:06:44 PM Tester main
Method: toString
Method: notify
Method: notifyAll
Method: wait
SEVERE: null
Method: wait
Method: wait
java.lang.NullPointerException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at Tester.main(Tester.java:40)
Just a note, the line number 40 is inaccurate because I removed comments and unnecessary portions to compact the above codes.
Why do I get a NullPointerException ? I tried to modify it to calling only the "getName()" method and it crashed too. How do I resolve this ?