… String[] args = new String[] {“-d”, “/homemytestclasses”, “Test.java”}; Int status = javac.compile(args); … javac编译工具被安装在JDK根目录的/bin目录下,负责将源代码编译成运行于JVM的字节码。事实上,我们经常使用/bin目录下的javac编译工具来编译Java源文件。如果在Java程序中动态编译任意制定的Java语句,使用这个外部的javac编译器就显得不够灵活了。虽然有时可使用Runtime类来执行一个外部命令,但如果想知道代码是否被编译通过、编译时发生了什么错误,用Runtime类的exec()方法就很难实现了。
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 :
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代码.