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);

}
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值