如何使用URLClassLoader加载* .class文件? [英] How to use URLClassLoader to load a *.class file?

查看:219
本文介绍了如何使用URLClassLoader加载* .class文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在玩Reflection,我想我会创建一个加载类的东西并打印出类中所有字段的名称。
我已经制作了一个小型的hello世界类型的类来检查:

I'm playing around with Reflection and I thought I'd make something which loads a class and prints the names of all fields in the class. I've made a small hello world type of class to have something to inspect:

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$ 

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

Based on the above I draw two conclusions:


  • 它存在于/home/kent/eclipsews/SmallExample/bin/IndependentClass.class

  • 它有效! (所以它必须是一个正确的.class文件,可以通过类加载器加载)

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

Then the code which is to use Reflection: (Line which causes an exception is marked)

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());
        }
    }
}

但是当我运行它时获取:

But when I run it I get:

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)

我的问题:


  1. 上面我做错了什么?我该如何解决?

  2. 有没有办法加载多个类文件并迭代它们?


推荐答案

来自 URLClassLoader(URL [])构造函数的Javadoc:

From the Javadocs for the URLClassLoader(URL[]) constructor:


使用默认委托父ClassLoader为指定的URL构造一个新的URLClassLoader。首次在父类加载器中搜索后,将按照为类和资源指定的顺序搜索URL。 任何以/结尾的网址都假定为引用目录。否则,URL被假定为引用JAR文件,该文件将根据需要下载和打开。

所以你有两个选项:


  1. 请参阅.class文件所在的目录

  2. 放入.class文件到一个JAR并引用那个

(1)在这种情况下更容易,但(2)可以很方便你正在使用网络资源。

(1) is easier in this case, but (2) can be handy if you're using networked resources.

这篇关于如何使用URLClassLoader加载* .class文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆