classLoader的动态加载实例

第一步:自定义一个类加载器
public class DynamicClassLoader extends ClassLoader{

public Class findClass(byte[] b) throws ClassNotFoundException {
return defineClass(null, b, 0, b.length);
}
}

第二步:创建一个管理类加载的类
package com.lhb;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class ManageClassLoader {

private DynamicClassLoader dc =null;

private Long lastModified = 0l;
private Class c = null;

/**
* 加载类, 如果类文件修改过加载,如果没有修改,返回当前的
* */
public Class loadClass(String fileName) throws ClassNotFoundException, IOException {
if (isClassModified(fileName)) {
dc = new DynamicClassLoader();
c = dc.findClass(getBytes(fileName));
}
return c;
}

/**
* 判断是否被修改过
* */
private boolean isClassModified(String fileName) {

boolean returnValue = false;
File file = new File(fileName);
if (file.lastModified() > lastModified) {
returnValue = true;
}
return returnValue;
}

/**
* 从本地读取文件
* */
private byte[] getBytes(String fileName) throws IOException {
File file = new File(fileName);

long len = file.length();

lastModified = file.lastModified();
byte[] buf = new byte[(int)len];
FileInputStream fis = new FileInputStream(file);
int r = fis.read(buf);
if (r != len) {
throw new IOException("Can't read all, " + r + " != " + len);
}
fis.close();
return buf;

}

public static void main(String[] args) throws ClassNotFoundException,
IOException, InstantiationException,
IllegalAccessException,
SecurityException, NoSuchMethodException,
IllegalArgumentException,
InvocationTargetException,
InterruptedException {

String path = "E:\\workspace_java\\Test_study\\bin\\com\\lhb\\LocalClass.class";
ManageClassLoader mc = new ManageClassLoader();
while(true){
Class c = mc.loadClass(path);
// 创建实例
Object o = c.newInstance();
Method m = c.getMethod("getName");
// 反射
m.invoke(o);
System.out.println(c.getClassLoader());
Thread.sleep(5000);

}
}
}

你可能感兴趣的:(JAVA综合)