我最近一直在玩Reflection API
并且我已成功拍摄了下面这样的一些电话,我正在从URLClassLoader
的jar档案中动态加载我的类:
public class JarUrlClassLoader {
public static void main(String args []){
File jarFile = new File("PATH_TO_JAR_ARCHIVE.jar");
String className = "org.test.MyClass";
try
{
URL fileURL = jarFile.toURI().toURL();
String jarURL = "jar:" + fileURL + "!/";
URL urls [] = { new URL(jarURL) };
URLClassLoader loader = new URLClassLoader(urls);
Object obj = Class.forName(className, true, loader).newInstance();
System.out.println("Object is: \"" + obj.toString() + "\"");
}
catch (MalformedURLException ex)
{
ex.printStackTrace();
}
catch (InstantiationException ex)
{
ex.printStackTrace();
}
catch (IllegalAccessException ex)
{
ex.printStackTrace();
}
catch (ClassNotFoundException ex)
{
ex.printStackTrace();
}
}
此代码段工作正常,似乎很容易理解。但是,当我试图进一步假设这个 jar文件已经在我的 Tomcat AS lib文件夹下时,该文件已经开始并且正在侦听某个端口。然后可以将此类org.test.MyClass
加载到JVM中,这样我就可以从那里加载它而不是从jar存档加载它。
所以我尝试了下面不起作用的代码片段:
public class RemoteUrlClassLoader {
private static final String httpURL = "http://localhost:8080/";
private static final String targetClass = "org.test.MyClass";
public static void main(String args[]) throws Exception {
System.out.println("Creating classloader for:" + httpURL);
URL[] urls = {new URL(httpURL)};
final ClassLoader newClassLoader = new URLClassLoader(urls);
Thread.currentThread().setContextClassLoader(newClassLoader);
System.out.println("Loading: " + targetClass);
Class urlClass = null;
try {
urlClass = newClassLoader.loadClass(targetClass);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
Object obj = null;
try {
obj = urlClass.newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
System.out.println("Object is: \"" + obj.toString() + "\"");
}
}
我在尝试执行此代码段时获得ClassNotFoundException
实际上我对这样的异常并不感到惊讶,但我确实需要澄清一下我是否可以做我想要实现的目标:从本地或远程JVM(正在运行的应用程序)加载一个类 ?
如果是,这个URL是httpURL = "http://localhost:8080/"
我需要更改的语句还是我必须更改整个类?
BR。