ClassLoader加载外部类
在桌面a文件夹创建了A.java,通过cmd命令在当前a目录下编译成A.class文件,然后运行如下代码:
public static void main(String[] args) throws Exception {
File file = new File("C:\\Users\\pactera\\Desktop\\a");
URL[] urls = {file.toURI().toURL()};
URLClassLoader urlClassLoader = new URLClassLoader(urls);
Class<?> a = urlClassLoader.loadClass("A");
System.out.println(a);
}
输出结果:
ClassLoader加载外部jar
在本地maven仓库中随便找了个jar
运行如下代码:
注意:URL中 -------------- jar协议 前缀格式固定为jar:file:/
public static void main(String[] args) throws Exception {
// 方式一
File file = new File("E:\\repository\\commons-io\\commons-io\\2.2\\commons-io-2.2.jar");
URL[] urls1 = {file.toURI().toURL()};
URLClassLoader urlClassLoader1 = new URLClassLoader(urls1);
Class<?> aClass1 = urlClassLoader1.loadClass("org.apache.commons.io.IOUtils");
System.out.println(aClass1);
// 方式二
URL url = new URL("jar:file:/E:/repository/commons-io/commons-io/2.2/commons-io-2.2.jar"+"!/");
URL[] urls = {url};
URLClassLoader urlClassLoader = new URLClassLoader(urls);
Class<?> ioUtils = urlClassLoader.loadClass("org.apache.commons.io.IOUtils");
System.out.println(ioUtils);
// 方式三
URLClassLoader systemClassLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
Method addURL = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
addURL.setAccessible(true);
addURL.invoke(systemClassLoader, url);
Class<?> aClass = systemClassLoader.loadClass("org.apache.commons.io.IOUtils");
System.out.println(aClass);
}
URL类支持如下协议
- http,https,ftp,mailto,file,jar,netdoc
测试如下:
package com.example.demo.test;
import java.net.MalformedURLException;
import java.net.URL;
public class TestURLProtocol {
public static void main(String[] args) {
String host = "www.baidu.com";
String file = "/index.html";
String[] schames = {"http", "https", "ftp", "mailto", "telnet", "file", "ldap", "gopher",
"jdbc", "rmi", "jndi", "jar", "doc", "netdoc", "nfs", "verbatim", "finger", "daytime",
"systemresource","webService","redis","zookeeper","rest","thrift","dubbo"};
for (int i= 0; i < schames.length; i++) {
try {
URL url = new URL(schames[i], host, file);
System.out.println(schames[i] + " is supported");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
System.out.println(schames[i] + " is not supported");
}
}
}
}