package snippet; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; /** * * @author Administrator *自定义类加载器 */ public class MyClassLoader extends ClassLoader { // 获取java源文件的二进制码 public byte[] getBytes(String filename){ File file = new File(filename); InputStream ips=null; byte[] b = new byte[(int) file.length()]; try { ips = new FileInputStream(file); int raw =ips.read(b); if(raw!=file.length()){ throw new IOException("无法完整读取文件"); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally{ if(ips!=null){ try { ips.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } return b; } public boolean compile(String javaFile){ System.out.println("正在编译"); Process p=null; try { //调用系统javac命令 p=Runtime.getRuntime().exec("javac" + javaFile); try { p.waitFor(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } int ret = p.exitValue(); return ret==0; } @Override protected Class<?> findClass(String name) { Class<?> clazz=null; String fileStub = name.replace(".", "/"); String javaFileName = fileStub + ".java"; String classFileName = fileStub + ".class"; File javaFile = new File(javaFileName); File classFile = new File(classFileName); //如果java源文件存在并且class文件不存在,或者java源文件比class文件修改的时间晚 if(javaFile.exists()&&(!classFile.exists()||javaFile.lastModified()>classFile.lastModified())){ if(!compile(javaFileName)||!classFile.exists()){ try { throw new ClassNotFoundException("未发现class文件"); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } //如果class文件已经存在,那么直接生成字节码 if(classFile.exists()){ byte[] b = getBytes(classFileName); clazz = defineClass(name, b, 0, b.length); } //如果为空,标明加载失败 if(clazz==null){ try { throw new ClassNotFoundException(name); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } return clazz; } } |