我正在尝试从类文件动态加载。下面的代码无法调用类中的方法。
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()”方法,但它也崩溃了。我该如何解决这个问题?