我想在每次调用我的方法时创建一个新的 ClassLoader
。
所以我可以在不退出程序的情况下重新加载 class
。
如何更新由 ClassLoader
加载的 class
的方法也是一种解决方案。
我怎样才能做到这一点?
最佳答案
我在这里找到了一个很好的解释性答案:
http://www.exampledepot.com/egs/java.lang/reloadclass.html
重要的是有两个二进制文件夹,在我的例子中: 一个用于测试用例,一个用于程序源。
引用:
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");
https://stackoverflow.com/questions/9819318/