-1
我正試圖從類文件中動態加載。下面的代碼無法調用該類中的方法。嘗試從動態類調用方法時出現NullPointerException
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) {
}
}
我努力的目標Java類調用:
public class TesterClass {
public hamster() {
}
public void getName() {
System.out.println("TEST SUCCEED !!!");
}
}
我得到了什麼:
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)
剛一說明,行號40是不準確的,因爲我刪除評論和不必要的部分來壓縮上面的代碼。
爲什麼我會得到NullPointerException?我試圖修改它只調用「getName()」方法,它也崩潰了。我該如何解決這個問題?
Object o = m1.invoke(null, null);
...一個例如方法: