相关疑难解决方法(0)

如何使用URLClassLoader加载*.class文件?

我正在玩Reflection,我想我会创建一个加载类的东西并打印出类中所有字段的名称.我已经制作了一个小型的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$ 
Run Code Online (Sandbox Code Playgroud)

基于以上所述我得出两个结论:

  • 它存在于/home/kent/eclipsews/SmallExample/bin/IndependentClass.class中
  • 有用!(所以它必须是一个正确的.class文件,可以由类加载器加载)

然后使用Reflection的代码:(标记导致异常的行)

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());
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

但当我运行它时,我得到:

Exception in thread "main" …
Run Code Online (Sandbox Code Playgroud)

java reflection

31
推荐指数
3
解决办法
8万
查看次数

标签 统计

java ×1

reflection ×1