Java 创建新的 ClassLoader 以重新加载类

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9819318/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 08:05:45  来源:igfitidea点击:

Create new ClassLoader to reload Class

javaclassbuild

提问by ctekk

I want to create a new ClassLoadereverytime my method is called.

ClassLoader每次调用我的方法时,我都想创建一个新的。

So I can reload a classwithout exiting my program.

所以我可以在class不退出我的程序的情况下重新加载 a 。

A way how I can update a classloaded by ClassLoaderwould also be a solution.

我如何更新class加载的ClassLoader方式也是一种解决方案。

How can I achieve that?

我怎样才能做到这一点?

采纳答案by ctekk

I found a good explained answer here:

我在这里找到了一个很好的解释答案:

http://www.exampledepot.com/egs/java.lang/reloadclass.html

http://www.exampledepot.com/egs/java.lang/reloadclass.html

The important thing is to have two binary folders, in my case: one for the testcases and one for the program source.

重要的是有两个二进制文件夹,就我而言:一个用于测试用例,另一个用于程序源。

Quote:

引用:

URL[] urls = null;
try {
    // Convert the file object to a URL
    File dir = new File(System.getProperty("user.dir")
        +File.separator+"dir"+File.separator);
    URL url = dir.toURL();        // file:/c:/almanac1.4/examples/
    urls = new URL[]{url};
} catch (MalformedURLException e) {
}

try {
    // Create a new class loader with the directory
    ClassLoader cl = new URLClassLoader(urls);

    // Load in the class
    Class cls = cl.loadClass("MyReloadableClassImpl");

回答by liam xu

saw this ? ClassLoader Load / Reload Example

看到了吗? 类加载器加载/重新加载示例

I think this blog can satisfy your requirement.

我认为这个博客可以满足您的要求。