/*
?* 建立日期 2004-7-2
?* 建立人 HongSoft
?* 檔案名稱 TestCompile.java
?*/
package com.hongsoft.test;
import java.io.*;
//定製的類裝入器
public class TestCompile extends ClassLoader
{
?String _compiler;
?String _classpath;
?public static void main(String[] args)
?{
??new TestCompile();
?}
?public TestCompile()
?{
??super(ClassLoader.getSystemClassLoader());
??//預設編譯器
??if (_compiler == null)
???_compiler = "D://j2sdk1.4.2//bin//javac";
??_classpath = ".";
??String extraclasspath =
???"c://Program Files//Java//j2re1.4.2//lib//rt.jar";
??// = System.getProperty("calc.classpath");
??if (extraclasspath != null)
??{
???_classpath =
????_classpath
?????+ System.getProperty("path.separator")
?????+ extraclasspath;
??}
??compile();
?}
?public void compile()
?{?????
??String filename = "";
??String classname = "";
??try
??{
???//建立臨時檔案
???File javafile =
????File.createTempFile("compiled_", ".java", new File("."));
???filename = javafile.getName();
???classname = filename.substring(0, filename.lastIndexOf("."));
???generateJavaFile(javafile, classname);
???//編譯檔案
???invokeCompiler(javafile);
???//建立java類
???byte[] buf = readBytes(classname + ".class");
???Class c = defineClass(buf, 0, buf.length);
???try
???{
???????c.newInstance();
???}
???catch (IllegalAccessException e)
???{
????throw new RuntimeException(e.getMessage());
???}
???catch (InstantiationException e)
???{
????throw new RuntimeException(e.getMessage());
???}
??}
??catch (IOException e)
??{
???throw new RuntimeException(e.getMessage());
??}
?}
?//產生java檔案
?void generateJavaFile(File javafile, String classname) throws IOException
?{
??FileOutputStream out = new FileOutputStream(javafile);
??String text =
???"public class "
????+ classname
????+ " {"
????+ " public int getCreater() {return 1;}"
????+ "}";
??out.write(text.getBytes());
??out.close();
?}
?//編譯java檔案
?void invokeCompiler(File javafile) throws IOException
?{
??String[] cmd =
???{ _compiler, "-classpath", _classpath, javafile.getName()};
??//執行編譯命令
??//A1:
??Process process = Runtime.getRuntime().exec(cmd);
??try
??{ //等待編譯器結束
???process.waitFor();
??}
??catch (InterruptedException e)
??{
??}
??int val = process.exitValue();
??if (val != 0)
??{
???throw new RuntimeException("編譯錯誤:" + "錯誤碼" + val);
??}
?}
?//以byte數組形式讀入類檔案
?byte[] readBytes(String filename) throws IOException
?{
???File classfile = new File(filename);
??byte[] buf = new byte[(int) classfile.length()];
??FileInputStream in = new FileInputStream(classfile);
??in.read(buf);
??in.close();
??return buf;
?}
}