写在前面
JAVA基础 - 如何使用ClassLoader?:https://blog.csdn.net/goodjava2007/article/details/130827943
JDK提供了一个更加易用的类加载器URLClassLoader,它扩展了ClassLoader,能够从本地目录、JAR包中以及网络指定位置加载类,建议使用该类作为自定义类加载器的父类。
// 继承关系如下:
package java.net;
public class URLClassLoader extends SecureClassLoader implements Closeable {}
...................
package java.security;
public class SecureClassLoader extends ClassLoader {}
加载方式
①. URLClassLoader 支持以下三种加载方式:
(1). 从本地文件系统目录中加载CLASS文件;
(2). 从本地文件系统目录的JAR包中加载CLASS文件;
(3). 从远程的HTTP服务的JAR包中加载CLASS文件。
②. 示例代码如下:
public class T2 {
public static void main(String[] args) throws Exception {
T2 t = new T2();
t.directory();
t.jar();
t.http();
}
public void directory() throws Exception {
System.out.println("从目录中加载CLASS文件.");
// CLASS的包路径: org.apache.atlas.util
// CLASS文件的存放路径: d:/org/apache/atlas/util
// URLClassLoader的加载路径: d:/
File file = new File("d:/");
URL url = file.toURI().toURL();
URLClassLoader classLoader = new URLClassLoader(new URL[]{url});
System.out.println(classLoader);
Class cls = classLoader.loadClass("org.apache.atlas.util.Hello1");
Object hello = cls.newInstance();
Method method = cls.getMethod("say1", null);
method.invoke(hello);
}
public void jar() throws Exception {
System.out.println("从本地目录的JAR包中加载CLASS文件.");
URL url = new URL("file:d:/atlas-webapp-2.1.0-classes.jar");
URLClassLoader classLoader = new URLClassLoader(new URL[]{url});
Class cls = classLoader.loadClass("org.apache.atlas.util.Hello2");
Object hello = cls.newInstance();
Method method = cls.getMethod("say2", null);
method.invoke(hello);
}
public void http() throws Exception {
System.out.println("从HTTP服务的JAR包中加载CLASS文件.");
URL url = new URL("http://192.168.64.174/atlas-webapp-2.1.0-classes.jar");
URLClassLoader classLoader = new URLClassLoader(new URL[]{url});
Class cls = classLoader.loadClass("org.apache.atlas.util.Hello3");
Object hello = cls.newInstance();
Method method = cls.getMethod("say3", null);
method.invoke(hello);
}
}