File file;
file = File.createTempFile(“JavaRuntime”, “.java”, new
File(System.getProperty(“user.dir”)));
String filename = file.getName();
String classname = getClassName(filename);
//将代码输出到文件
PrintWriter out = new PrintWriter(new FileOutputStream(file));
out.println(“public class” + classname + “ {”};
out.println(“..代码..”);
out.println(“}”);
//关闭文件流
out.flush();
out.close();
我们约定被创建的临时文件名以“JavaRuntime”为头缀(可任意命名),后缀名以“.java”结尾。一个待编译的Java源文件已被动态生成。下一步要从com.sun.tools.javac包中创建一个Main实例,调用javac.compile()方法编译这个临时文件:
Private static com.sun.tools.javac.Main javac = new
com.sun.tools.javac.Main();
String[] args = new String[] {“-d”,
System.getProperty(“user.dir”),filename };
Int status = javac.compile(args);
假定临时文件通过了编译器文法验证等验证,编译成功(status值等于0,参看前表),在当前程序的运行目录下就会多了一个Java类文件。我们将通过执行这个Java
类文件,来模拟执行欲动态编译代码的结果。
Java提供在运行时刻加载类的特性,可动态识别和调用类构造方法、类字段和类方法。java.lang.reflect.Method实现了Member接口,可以调用接口的方法来获得方法类的名称、修饰词等。方法getRuturnType()、getParameterTypes()、getExeptionTypess()等返回被表示方法的构造信息。Method另一个重要的特性是可以调用invoke()执行这个方法(详细使用方法可以查看java.lang.reflect包文档)。下面这段代码中创建一个java.lang.reflect.Method类方法,调用getMethod()方法获得被拼装的main方法的映射,这段代码如下:
try {
// 访问这个类
Class cls = Class.forName(classname);
//调用main方法
Method main = cls.getMethod(“main”, new Class[] { String[].class
});
main.invoke(null, new Object[] { new String[0] });
}catch (SecurityException se) {
debug(“access to the information is denied:” + se.toString());
}catch (NoSuchMethodException nme) {
debug(“a matching method is not found or if then name is or :
” + nme.toString());
}catch (InvocationTargetException ite) {
debug(“Exception in main: ” + ite.getTargetException());
}catch (Exception e){
debug(e.toString());
}
运行结果参如下:
Hello,This runtime code!
示范程序
下面给出了一个简单的Java程序,这个程序说明了如何利用Sun的javac编译器完成动态编译Java语句。运行该程序需要计算机安装JDK
1.2以上版本,并在classpath中或运行时指定tools.jar文件位置。
程序结构:
◆ compile() 编译Java代码,返回生成的临时文件;
◆ run()运行编译的class文件;
◆ debug()输出调试信息;
◆ getClassName()从一个Java源文件获得类名;
◆ readLine()从控制台读取用户输入的Java Code。
Import java.io.File;
…
Public class RuntimeCode{
/**编译器*/
private static com.sun.tools.javac.Main javac = new
com.sun.tools.javac.Main();
/**等待用户输入JavaCode,然后编译、执行*/
public static void main(String[] args) throws Exception{
…
run(compile(code));
}
/**编译JavaCode,返回临时文件对象*/
private synchronized static File compile(String code)
throws IOException,Exception {
File file;
//在用户当前文件目录创建一个临时代码文件
file = File.createTempFile(“JavaRuntime”, “.java”,
new File(System.getProperty(“user.dir”)));
//当虚拟机退出时,删除此临时java源文件
file.deleteOnExit();
//获得文件名和类名字
String filename = file.getName();
String classname = getClassName(filename);
//将代码输出到文件
PrintWriter out = new PrintWriter(new FileOutputStream(file));
out.println(“/**”);
…
//关闭文件流
out.flush();
out.close();
//编译代码文件
String[] args = new String[] {“-d”,
System.getProperty(“user.dir”),filename };
//返回编译的状态代码
int status = javac.compile(args);
//处理编译状态
…
}
/**执行刚刚编译的类文件*/
private static synchronized void run(File file)
…
//当虚拟机退出时,删除此临时编译的类文件
new File(file.getParent(), classname + “.class”).deleteOnExit();
try {
// 访问这个类
Class cls = Class.forName(classname);
//映射main方法
Method main = cls.getMethod(“main”, new Class[] { String[].class
});
//执行main方法
main.invoke(null, new Object[] { new String[0] });
}catch (SecurityException se) {
…
}
}
/**打印调试信息*/
private static void debug(String msg) {
System.err.println(msg);
}
/**根据一个java源文件名获得类名*/
private static String getClassName(String filename){
return filename.substring(0,filename.length()-5);
}
/**从控制台获得用户输入的Java代码段*/
…
}
编译运行上述代码,在please input java
code提示下输入以下代码:
for(int i=0;i<10;i++){System.out.println(“this is:”+i);}
运行结果如下所示:
Please input java code:
for(int i=0;i<10;i++){System.out.println(“this is:”+i);}
wait....
--------------------
this is:0
this is:1
this is:2
this is:3
this is:4
this is:5
this is:6
this is:7
this is:8
this is:9