package cn.itcast.myclassloader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
/**
*
* @author ETHAN
*protected synchronized Class<?> loadClass(String name, boolean resolve)
throws ClassNotFoundException
{
// First, check if the class has already been loaded
Class c = findLoadedClass(name);
if (c == null) {
try {
//先找父类加载器
if (parent != null) {
//loadClass()再去找父类加载器
c = parent.loadClass(name, false);
} else {
//parent=null,说明是根加载器bootstrap
c = findBootstrapClass0(name);
}
//否则就自己去找
} catch (ClassNotFoundException e) {
// If still not found, then invoke findClass in order
// to find the class.
c = findClass(name);
}
}
if (resolve) {
resolveClass(c);
}
return c;
}
*/
/*
* loadClass() 还是要去调用 findClass
*
* 应用程序可以创建一个网络类加载器,从服务器中下载类文件。示例代码如下所示:
ClassLoader loader = new NetworkClassLoader(host, port);
Object main = loader.loadClass("Main", true).newInstance();
网络类加载器子类必须定义方法 findClass 和 loadClassData,以实现从网络加载类。下载组成该类的字节后,它应该使用方法 defineClass 来创建类实例。示例实现如下:
class NetworkClassLoader extends ClassLoader {
String host;
int port;
public Class findClass(String name) {
byte[] b = loadClassData(name);
return defineClass(name, b, 0, b.length);
}
private byte[] loadClassData(String name) {
// load the class data from the connection
. . .
//URLConnection(url).getInputStream()
}
}
*/
public class MyClassloader extends ClassLoader {
//查找class文件
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
//cn.itacast.myclassloader.Person---->cn\\itacast\\myclassloader\\Person.class
String clsName = name.replace(".", "\\")+".class";
InputStream in = MyClassloader.class.getClassLoader().getResourceAsStream(clsName);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int len = 0;
try {
while((len = in.read(buf))!=-1) {
bos.write(buf,0,len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
in.close();
bos.flush();
bos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//获取字节码文件
byte[] classbytes = bos.toByteArray();
return this.defineClass(name, classbytes, 0, classbytes.length);
}
}
package cn.itcast.myclassloader;
public class Person {
@Override
public String toString() {
return "person...........";
}
}
package cn.itcast.myclassloader;
public class Test {
/**
* @param args
* @throws ClassNotFoundException
*/
public static void main(String[] args) throws ClassNotFoundException {
MyClassloader mc = new MyClassloader();
//Class clazz = mc.findClass("cn.itcast.myclassloader.Person");
Class clazz = mc.findClass("cn.itcast.myjunit.HelloJunit");
try {
System.err.println(clazz.newInstance());
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}