jvm第六节-类加载器
分别把相同的类放在不同的目录下,分别答应不同的类容
public class HelloClassLoader{ public static void main(String[]args){ System.out.println("i am in bootclassloader"); } }如图
可以证明类加载器是从顶向下加载的
建立4个类代码分别如下:
第一个类:
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class Worker {
public void doit(){
Calendar cd = Calendar.getInstance();
cd.setTime(new Date());
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:MM:ss");
String date=sdf.format(new Date());
System.out.println("hello do it==" + date);
}
}
public class MyClassLoader extends ClassLoader {
public Class<?> findClass(byte[] b) throws ClassNotFoundException {
return defineClass(null, b, 0, b.length);
}
}
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
/**
* 自定义类加载
* @Author:xuehan
* @Date:2016年2月27日下午5:00:38
*/
public class MyclassLoaderUtils{
// 最后一次被修改时间
long lastmTime = System.currentTimeMillis();
// 判断class文件是否被修改过
public boolean isClassModified(String fileName){
File file = new File(fileName);
if(file.lastModified() - lastmTime > 0){
System.out.println("文件被修改");
lastmTime = System.currentTimeMillis();
return true;
}
return false;
}
// 从本地读取文件
@SuppressWarnings("unused")
private byte[] getClassBytes(String filename) throws IOException {
File file = new File(filename);
long len = file.length();
lastmTime = file.lastModified();
byte raw[] = new byte[(int) len];
FileInputStream fin = new FileInputStream(file);
int r = fin.read(raw);
fin.close();
return raw;
}
//加载类, 如果类文件修改过加载,如果没有修改,返回当前的
public Class loadClass(String name) throws ClassNotFoundException, IOException{
Class c = null;
if (isClassModified(name)){
MyClassLoader mc = new MyClassLoader();
return c = mc.findClass(getClassBytes(name));
}
return c;
}
第四个类:
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* 虚拟机加载入口的地方
* @Author:xuehan
* @Date:2016年2月27日下午5:33:14
*/
public class HelloMain {
@SuppressWarnings({ "rawtypes", "unchecked" })
public static void main(String[] args)
throws ClassNotFoundException, IOException, NoSuchMethodException, IllegalAccessException,
IllegalArgumentException, InvocationTargetException, InstantiationException, InterruptedException {
String path = "D:\\Users\\workspace\\jvm\\src\\main\\java\\com\\jvm\\day3\\Worker.class";
MyclassLoaderUtils mc = new MyclassLoaderUtils();
while (true) {
Class c = mc.loadClass(path);
if(null == c){
c = Worker.class;
}
Object o = c.newInstance();
Method m = c.getMethod("doit");
m.invoke(o);
Thread.sleep(2000);
}
}
}