HelloWorld 善战者,求之于势,不责于人;故能择人而任势。

知止而后有定,定而后能静,静而后能安,安而后能虑,虑而后能得。物有本末,事有终始。知所先后,则近道矣。

  BlogJava :: 首页 ::  :: 联系 ::  :: 管理 ::
  167 随笔 :: 1 文章 :: 40 评论 :: 0 Trackbacks

import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import com.sun.tools.javac.Main;

class ExecJava {
public static void runJava(String code) {
    File file;
    Main javac = new Main();
    String classname = "";
    String filename = "";
    String path = System.getProperty("user.dir")+"\\work";
    try {
     // 在当前目录下产生一个临时JAVA文件
     file = new File(path+"\\TTTTT.java");
     file.createNewFile();
     // 当程序离开时删除这个临时文件
     filename = file.getName();
     classname = getClassName(filename);

     // 写临时文件
     PrintWriter out = new PrintWriter(new FileOutputStream(file));
     out.print("package com.work;\r\n");
     out.print("public class " + classname + "{\r\n");
     out.print("\tpublic static void main(String[] test) {\r\n");
     out.print("\t\t");
     out.println(code);
     out.println("test();");
     out.println("\t}");
     out.print("\tpublic static void test() {\r\n");
     out.print("\t\t");
     out.println(code);
     out.println("\t}");
     out.println("\r\n}");
     out.flush();
     out.close();
     // 编译执行临时文件
     String[] args = new String[] { "-d",path, path+"\\"+ filename };
     int status = javac.compile(args);
     new File(file.getParent(), classname + ".class");
//     System.out.println(classname);
     System.setProperty("java.class.path", path);
   
     Class clss = Class.forName("com.work.TTTTT");
     System.out.println(clss.getPackage());
     Method m = clss.getMethod("test", null);
     m.invoke(clss,null);
    } catch (Exception e) {
     e.printStackTrace();
     System.out.println(e);
    }
}

/** 根据一个java源文件名获得类名 */
private static String getClassName(String filename) {
    return filename.substring(0, filename.length() - 5);
}

public static void main(String args[]) {
    runJava("System.out.println(\"test\");");
}
}



</script>

posted on 2007-08-13 18:52 helloworld2008 阅读(609) 评论(0)  编辑  收藏 所属分类: java

只有注册用户登录后才能发表评论。


网站导航: