at java.net.urlclassloader.findclass_如何使用URLClassLoader加载* .class文件?
我在玩反射,我想做點東西來加載一個類并打印該類中所有字段的名稱。我制作了一個小型的hello world類型的類來檢查一些東西:
kent@rat:~/eclipsews/SmallExample/bin$ ls
IndependentClass.class
kent@rat:~/eclipsews/SmallExample/bin$ java IndependentClass
Hello! Goodbye!
kent@rat:~/eclipsews/SmallExample/bin$ pwd
/home/kent/eclipsews/SmallExample/bin
kent@rat:~/eclipsews/SmallExample/bin$
基于以上所述,我得出兩個結論:
它存在于/home/kent/eclipsews/SmallExample/bin/IndependentClass.class
有用!(因此它必須是可以由類加載器加載的正確的.class文件)
然后使用反射的代碼:(標記導致異常的行)
import java.lang.reflect.Field;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
public class InspectClass {
@SuppressWarnings("unchecked")
public static void main(String[] args) throws ClassNotFoundException, MalformedURLException {
URL classUrl;
classUrl = new URL("file:///home/kent/eclipsews/SmallExample/bin/IndependentClass.class");
URL[] classUrls = { classUrl };
URLClassLoader ucl = new URLClassLoader(classUrls);
Class c = ucl.loadClass("IndependentClass"); // LINE 14
for(Field f: c.getDeclaredFields()) {
System.out.println("Field name" + f.getName());
}
}
}
但是當我運行它時,我得到:
Exception in thread "main" java.lang.ClassNotFoundException: IndependentClass
at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at java.lang.ClassLoader.loadClass(ClassLoader.java:251)
at InspectClass.main(InspectClass.java:14)
我的問題:
上面我在做什么錯?我如何解決它?
有沒有辦法加載幾個類文件并對其進行迭代?
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的at java.net.urlclassloader.findclass_如何使用URLClassLoader加载* .class文件?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 只会安琪拉可以打到王者吗 汉典只字的基本
- 下一篇: 洋葱学院怎么样,会有提升吗(洋葱洋葱的功