It looks like reflection, however, I do not think it possible to use String as a line  of code.

解决方案 »

  1.   

    只好用笨办法了:
    在程序中将要执行的东西写入一个java文件中,然后调用javac编译,再用forName()动态装入类来运行。
      

  2.   

    例如 javascript 和 PHP 等语言都有类似的操作啊 例如在 javascript中有: eval("var a = 5 + 6;"); document.writeln(a); 输出11。这样的操作狠有用的,例如用字符串拼凑出表达式,然后运行。
      

  3.   

    to  stonefeng(浩)请问如何调用javac编译?能给一段代码吗?谢谢!
      

  4.   

    Runtime.run("javac ...");
    其中的...表示你传给javac的参数,应该不用我再说了,自己把它补全吧。:)
      

  5.   

    不好意思,记错了,应该是:
    Runtime.exec("javac ...");
      

  6.   

    to  stonefeng(浩)那编译完后,怎么调用实现呢?谢谢
      

  7.   

    经过大家的指点,我终于有点眉目了,写了一个简单的例子,共享出来,谢谢大家的帮助。import java.io.*;
    import java.lang.reflect.*;
    public class  Execexpression
    {
    public static void main(String[] args) 
    {
    Execexpression c = new Execexpression();
    String express = "int a = 5 + 6;";
    String s = c.execString(express);
    System.out.println(s);
    } private String execString(String express){
    try{
    String strClass = "public class DynamicExpress{\n\r public static void main(String[] args) {\n\r System.out.println(\"Hello World!\"); \n\r } \n\r public static int ret(){ \n\r  " + express + " \n\r return a; \n\r } \n\r }";
    File file = new File("DynamicExpress.java");

    if(!file.exists()){
    file.createNewFile();
    }
    FileOutputStream out = new FileOutputStream(file);
    out.write(strClass.getBytes());
    out.close();
    Runtime.getRuntime().exec("javac DynamicExpress.java");  file = new File("DynamicExpress.class");
    while(!file.exists()){
    if(file.exists()){
    break;
    }
    } Class c = Class.forName("DynamicExpress");
    Object o = c.newInstance();
    Method m = c.getMethod("ret", null);
    Integer ret = (Integer) m.invoke(o, null);
    String s = ret.toString();
    return s;
    }
    catch(Exception e){
    e.printStackTrace();
    return "sorry!";
    } }
    }
      

  8.   

    看上去你似乎是想写一个java语言的解释器?
      

  9.   

    to sunwanshu(痴心绝对):
    嗯,基本上符合我说的那个思路。