Java动态加载类的问题

标签 java dynamic-class-loaders

我正在尝试编写一个代码,在从字符串创建另一个 java 类之后编译并运行它。

我的问题是当我运行时

    Class classToLoad = null;
    ClassLoader classLoader = Server.class.getClassLoader();
    try {
        classToLoad = classLoader.loadClass(className);
    } catch (Exception e) {
        e.printStackTrace();
    }

它抛出 ClassNotFoundException。我的问题与包无关,因为如果我调试代码并在“getClassLoader”之前放置断点,然后重新加载类,那么我的代码可以正常工作,并且它会看到最近在应用程序中较早创建的类。< br/>
如何在运行时重新加载类以便 loadClass 正常工作?

最佳答案

看看这个 tutorial :

类加载器加载/重新加载示例

... Let's look at a simple example. Below is an example of a simple ClassLoader subclass. Notice how it delegates class loading to its parent except for the one class it is intended to be able to reload. If the loading of this class is delegated to the parent class loader, it cannot be reloaded later. Remember, a class can only be loaded once by the same ClassLoader instance.

As said earlier, this is just an example that serves to show you the basics of a ClassLoader's behaviour. It is not a production ready template for your own class loaders. Your own class loaders should probably not be limited to a single class, but a collection of classes that you know you will need to reload. In addition, you should probably not hardcode the class paths either.

public class MyClassLoader extends ClassLoader{

    public MyClassLoader(ClassLoader parent) {
        super(parent);
    }

    public Class loadClass(String name) throws ClassNotFoundException {
        if(!"reflection.MyObject".equals(name))
                return super.loadClass(name);

        try {
            String url = "file:C:/data/projects/tutorials/web/WEB-INF/" +
                            "classes/reflection/MyObject.class";
            URL myUrl = new URL(url);
            URLConnection connection = myUrl.openConnection();
            InputStream input = connection.getInputStream();
            ByteArrayOutputStream buffer = new ByteArrayOutputStream();
            int data = input.read();

            while(data != -1){
                buffer.write(data);
                data = input.read();
            }

            input.close();

            byte[] classData = buffer.toByteArray();

            return defineClass("reflection.MyObject",
                    classData, 0, classData.length);

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

}

Below is an example use of the MyClassLoader.

public static void main(String[] args) throws
    ClassNotFoundException,
    IllegalAccessException,
    InstantiationException {

    ClassLoader parentClassLoader = MyClassLoader.class.getClassLoader();
    MyClassLoader classLoader = new MyClassLoader(parentClassLoader);
    Class myObjectClass = classLoader.loadClass("reflection.MyObject");

    AnInterface2       object1 =
            (AnInterface2) myObjectClass.newInstance();

    MyObjectSuperClass object2 =
            (MyObjectSuperClass) myObjectClass.newInstance();

    //create new class loader so classes can be reloaded.
    classLoader = new MyClassLoader(parentClassLoader);
    myObjectClass = classLoader.loadClass("reflection.MyObject");

    object1 = (AnInterface2)       myObjectClass.newInstance();
    object2 = (MyObjectSuperClass) myObjectClass.newInstance();

}

关于Java动态加载类的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32297275/

相关文章:

java - 在 NeoMAD 项目中使用 java.util.Iterator 时出错

java - 对具有重试逻辑的方法进行单元测试

programming-languages - 哪些框架(和相关语言)支持类替换?

Java反射,如何在运行时重新加载已更改和重新编译的类?

java - 尝试在运行时从外部 JAR 加载类时出现 ClassNotFoundException

Java 类加载器俄罗斯套娃

java - 检查某个异常类型是否是嵌套异常中的原因(原因等)的最佳方法?

Java NullPointerException - 我可以告诉空对象的类吗?

Java将Mysql查询结果放入multimap中

python - Python 2.6 中的动态类加载 : RuntimeWarning: Parent module 'plugins' not found while handling absolute import