自定义类加载器

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

/**
 * 动态的编译Java源文件。它检查.class文件是否存在,.class文件是否比源文件陈旧。
 */
public class CompilingClassLoader extends ClassLoader {

	private String path = "";

	public CompilingClassLoader(String path) {
		this.path = path;
	}

	/**
	 * 从磁盘读取指定文件,并返回字节数组
	 */
	private byte[] getBytes(String className) {
		FileInputStream in = null;
		byte[] raw = null;
		try {
			File file = new File(className);
			in = new FileInputStream(file);
			raw = new byte[(int) file.length()];
			int r = in.read(raw);
			if (r == file.length()) {
				return raw;
			}
		} catch (IOException ex) {
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return null;
	}

	/**
	 * 启动一个进程来编译java源文件
	 */
	private boolean compile(String javaFile) {
		try {
			Process p = Runtime.getRuntime().exec("javac " + javaFile);
			p.waitFor(); // 等待编译结束
			int res = p.exitValue(); // 检查返回码,看编译是否成功
			return res == 0;
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (IOException ex) {
			ex.printStackTrace();
		}
		return false;
	}

	/**
	 * 动态的编译Java源文件。它检查.class文件是否存在,.class文件是否比源文件陈旧。
	 */
	protected Class<?> findClass(String className)
			throws ClassNotFoundException {
		Class<?> cls = this.findLoadedClass(className);
		if (cls == null) {
			String fileName = className.replace('.', File.pathSeparatorChar);
			String javaFileName = path + fileName + ".java";
			String classFileName = path + fileName + ".class";
			File javaFile = new File(javaFileName);
			File classFile = new File(classFileName);
			if (!classFile.exists() && javaFile.exists()
					|| javaFile.lastModified() > classFile.lastModified()) {
				if (!compile(javaFileName)) {
					throw new ClassNotFoundException(className);
				}
			}
			byte[] raw = getBytes(classFileName);
			if (raw == null) {
				throw new ClassNotFoundException(className);
			}
			cls = this.defineClass(className, raw, 0, raw.length);
		}
		return cls;
	}

	public static void main(String[] args) throws Exception{
		CompilingClassLoader ccl = new CompilingClassLoader("e:/");
		Class<?> c = ccl.findClass("Test");
		Method method = c.getDeclaredMethod("print", new Class<?>[] {});
		method.invoke(c.newInstance(), new Object[] {});
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值