package com.load;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.ConcurrentHashMap;
public class Client2 {
public NetClassLoder classLoader;
@Test
public void test() throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException, InterruptedException {
String domain = "http://localhost";
URL clas = new File(domain).toURI().toURL();
int i = 0;
ConcurrentHashMap<String, ClassLoader> map = new ConcurrentHashMap<>();
String name= "a"+i;
i++;
System.out.println("++++");
classLoader = new NetClassLoder(domain);
Class<?> aClass = classLoader.findClass("com.load.plugin.impl.DemoFunction");
System.out.println(aClass);
boolean assignableFrom = IFunction.class.isAssignableFrom(aClass);
System.out.println(assignableFrom);
IFunction o = (IFunction) aClass.newInstance();
o.test();
classLoader = new NetClassLoder(domain);
Class<?> aClass3 = classLoader.findClass("com.load.plugin.impl.DemoFunction");
System.out.println(aClass);
boolean assignableFrom3 = IFunction.class.isAssignableFrom(aClass);
System.out.println(assignableFrom3);
IFunction o2 = (IFunction) aClass.newInstance();
o2.test();
System.gc();
o.test();
System.out.println(IFunction.class.getClassLoader());
System.out.println(o2.getClass().getClassLoader());
}
}
package com.load;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.URL;
public class NetClassLoder extends ClassLoader {
private String url;
public NetClassLoder(String url){
this.url=url;
}
@Override
protected void finalize() throws Throwable {
System.out.println("类加载器回收了");
}
@Override
protected Class<?> findClass(String className) throws ClassNotFoundException {
byte[] classByNet = findClassByNet(className);
if(classByNet==null){
throw new ClassNotFoundException();
}
return defineClass(className,classByNet,0,classByNet.length);
}
protected byte[] findClassByNet(String className){
String path = pares2Url(className);
try {
URL url = new URL(path);
InputStream ins = url.openStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int bufferSize = 4096;
byte[] buffer = new byte[bufferSize];
int bytesNumRead = 0;
while ((bytesNumRead = ins.read(buffer)) != -1) {
baos.write(buffer, 0, bytesNumRead);
}
return baos.toByteArray();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private String pares2Url(String className) {
String replace = className.replace(".", "/");
return url+"/"+replace+".class";
}
}