`
kongshanxuelin
  • 浏览: 913251 次
  • 性别: Icon_minigender_1
  • 来自: 宁波
社区版块
存档分类
最新评论

动态运行Java代码

阅读更多

有些情况下,我们不得不动态运行Java代码,以便提供更加灵活的方式,以下代码可参考(在JDK 1.5+平台上运行通过):

	public static void main(String[] args) {
//		PrintWriter out;
//		PrintStream myOut = new PrintStream(out);
//		System.setOut(myOut);
//		System.setErr(myOut);

		int i = 10;
		String code = "System.out.println(\"Hello World!\"+(13+2*5/3));";
		code += "for(int i=0;i<" + i + ";i++){";
		code += " System.out.println(Math.pow(i,2));";
		code += "}";
		try {
			run(code);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private synchronized static File compile(String code) throws Exception {
		File file = File.createTempFile("JavaRuntime", ".java", new File(System
				.getProperty("user.dir")));
		file.deleteOnExit();

		//		获得类名 
		String classname = getBaseFileName(file);

		//		将代码输出到文件 
		PrintWriter out = new PrintWriter(new FileOutputStream(file));
		out.println(getClassCode(code, classname));
		out.close();

		//		编译生成的java文件 
		String[] cpargs = new String[] { "-d",
				System.getProperty("user.dir") + "\\WebRoot\\WEB-INF\\classes",
				file.getName() };
		int status = Main.compile(cpargs);
		if (status != 0) {
			throw new Exception("语法错误!");
		}

		return file;
	}

	private static synchronized void run(String code) throws Exception {
		String classname = getBaseFileName(compile(code));
		new File(System.getProperty("user.dir")
				+ "\\WebRoot\\WEB-INF\\classes\\" + classname + ".class")
				.deleteOnExit();
		try {
			Class cls = Class.forName(classname);
			Method main = cls.getMethod("method", null);
			main.invoke(cls, null);
		} catch (Exception se) {
			se.printStackTrace();
		}
	}

	private static String getClassCode(String code, String className) {
		StringBuffer text = new StringBuffer();

		text.append("public class " + className + "{\n");
		text.append(" public static void method(){\n");
		text.append(" " + code + "\n");
		text.append(" }\n");
		text.append("}");

		return text.toString();
	}

	private static String getBaseFileName(File file) {
		String fileName = file.getName();
		int index = fileName.indexOf(".");
		String result = "";
		if (index != -1) {
			result = fileName.substring(0, index);
		} else {
			result = fileName;
		}
		return result;
	}
 
分享到:
评论
6 楼 timonzhang 2008-12-16  
       1.6里可以使用JavaCompiler和JavaCompiler.CompilationTask 实现。问题是这些只算做到了动态编译,不算真正意义上的动态运行
5 楼 bloodrate 2008-12-16  
Main.compile
貌似不在标准的jdk lib里阿
4 楼 bluky999 2008-12-15  
请问上述代码中的 Main 类是哪个Main ?????

 int status = Main.compile(cpargs);  
 if (status != 0) {  
       throw new Exception("语法错误!");  
 }  
3 楼 stephen_chenxifei 2008-09-19  
正在被使用的class,使用动态运行java代码,就不用重新启动服务了,相当于热发布这个class,是不是可以这样理解,需要研究下下,现在每次发布更新程序,真是搞死了人了。
2 楼 longlongriver 2008-09-19  
cnhzliye 写道
用beanshell

正解!这种场景非常适合用脚本中间件!
1 楼 cnhzliye 2008-09-19  
用beanshell

相关推荐

Global site tag (gtag.js) - Google Analytics