一直被一个java问题困惑。
比如:String a="3+2";
如何执行字符串a中的算术。
又比如:
int i=0;
int y=3;
String a="i+y";
如果把字符串a中的2个变量相加得到3呢?
查了一下javascript中有个eval()的函数可以实现上面的功能。
但是在java中如何实现呢?
请大家帮忙一起解决,发现这个问题满有意思的!
比如:String a="3+2";
如何执行字符串a中的算术。
又比如:
int i=0;
int y=3;
String a="i+y";
如果把字符串a中的2个变量相加得到3呢?
查了一下javascript中有个eval()的函数可以实现上面的功能。
但是在java中如何实现呢?
请大家帮忙一起解决,发现这个问题满有意思的!
int y=3;
String a=i+y+"";
这样就OK了!
是外部定义的函数,是读进来的。
SignStack //存放运算符
NumStack //存放运算数利用2个栈分析字符串,就可以了,具体可以找本编译原理的书看看.
javascript是解释执行,当然可以再运行中宏替换
可以这样:
String str = "" + i + j;
${ i+y }
{
int flag=String.indexOf("+");
int Ivariable1,Ivariable2;
variable1=String.subString(0,flag);
Ivariable1=Integer.parstInt(variable1);
variable2=String.subString((flag + 1));
Ivariable2=Integer.parstInt(variable2);
return Ivariable2+Ivariable1;}这种可以?
* 创建日期 2005-6-24
*/
package test;import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import sun.tools.javac.Main;/**
* @author c44196
*/
public class Test {
public static void main(String[] args) throws Exception {
String s = "public class Test3 {public static int i=3+4;}";
File file = new File("Test3.java");
FileOutputStream fos = new FileOutputStream(file);
fos.write(s.getBytes());
fos.close();
System.out.println(file.getPath());
Main main = new Main(System.out, "javac");
main.compile(new String[] { file.getPath() });
ClassLoader loader = new ClassLoader() {
protected Class findClass(String name) throws ClassNotFoundException {
Class c = null;
try {
File file = new File("Test3.class");
byte[] bytes = new byte[(int) file.length()];
FileInputStream fis = new FileInputStream(file);
fis.read(bytes);
fis.close();
c = defineClass(bytes, 0, bytes.length);
} catch (Exception e) {
e.printStackTrace();
}
return c;
}
};
Class c = loader.loadClass("Haha");
Object obj = c.newInstance();
System.out.println(obj.getClass());
System.out.println(c.getField("i").get(obj));
}
}
导入之后估计就可以调用eval()函数了