动态编译Java程序
在sun jdk 1.2及后续版本中,包含了一组可在程序运行时刻编译和执行java代码的api。这些api被包含在tools.jar类库中。这个功能允许java程序在运行时动态编译、执行小的代码块,在有些情况下这个功能会让java应用程序的架构更加灵活、开放。本文假定读者已经在计算机中安装并配置好了sun jdk 1.2或更高的版本,并对javac编译器命令有所了解。
在java程序中使用编译器
假定要使用javac命令编译 /home/mytest目录下test.java文件,并设定class文件存放在/home/mytest/classes路径下,输入下面命令:
javac -d /home/mytest/classes test.java
达到同样的目的,也可以使用sun提供的一个java编译器的api来实现。它的使用也很简单,核心代码段如下:
…
string[] args = new string[] {“-d”, “/home/mytest/classes”, “test.java”};
int status = javac.compile(args);
…
javac编译工具被安装在jdk根目录的/bin目录下,负责将源代码编译成运行于jvm的字节码。事实上,我们经常使用/bin目录下的javac编译工具来编译java源文件。如果在java程序中动态编译任意制定的java语句,使用这个外部的javac编译器就显得不够灵活了。虽然有时可使用runtime类来执行一个外部命令,但如果想知道代码是否被编译通过、编译时发生了什么错误,用runtime类的exec()方法就很难实现了。
在sun的jdk 1.2及后续版本中,jdk安装路径的/lib路径下包含了一个tools.jar文件,这个类库包含了一个完整的编译器包。com.sun.tools.javac.main是编译器的主类入口,如果已经熟悉了javac编译器命令行的使用方法,很容易理解这个类的使用方法。方法compile(string[] p)执行编译动作,参数p是一个string数组,用来存放javac命令的参数选项,编译后的状态返回一个int值,其对应值参考如下表所示:
表 状态参数与对应值
exit_ok 0
exit_error 1
exit_cmderr 2
exit_syserr 3
exit_abnormal 4
在程序执行时编译和执行java语句
从上面一段中,我们已经基本了解了动态编译一个java文件的方法。那么,如何运行时动态编译指定的java语句呢?这里需要一个技巧。
假设要动态编译的java条语句如下:
system.out.println(“hello,this runtime code!”);
编译器不支持编译单个java语句,被编译的对象必须是一个以.java为后缀的、结构合法的类源程序文件,所以需要对这个语句进行改造,变成一个完整的类,并把这条语句置入main方法中,便于测试。
public class <临时类文件名> {
public static void main(string[] args) throws exception {
system.out.println(“hello,this runtime code!”);
}
}
这样,欲动态编译的代码已经被程序动态拼装成了上面那段代码,准备工作还没有结束,不过看起来工作在趋向稍微的复杂化。因为上述代码当前还存放在内存中,编译器似乎对一个硬盘文件更感兴趣。我们需要引用java.io.file类(jdk 1.2以上),创建一个临时的文件来存放上述代码的内容。java.io.file类的静态方法createtempfile()方法保证所创建的文件名是不重复的,这样会增大这段程序的灵活性。灵活性取决于真正应用到系统架构中的策略。
system.getproperty(“user.dir”)用来获得当前路径,在这里作为临时文件的存放目录。
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 });
}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 });
}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
**总结:
在大中型企业应用系统平台中,使用代码动态编译技术结合oo编程模型,可在系统不菪机条件下保证系统的可扩展性和伸缩性。如果你是一个java程序员,稍加调整以上代码,还可以帮助调试小段的java代码。 太麻烦了,直接用Netbeans不就好了!
页:
[1]