Java 将字符串动态生成字节码的实现方法
可以生成可执行的class文件
直接上能执行代码:
public class test {
/**
* @param args
*/
@suppresswarnings("static-access")
public static void main(string[] args) {
try {
new test().calculate("234 - ( 1 + 45 * 4 ) / 5");
} catch (exception e) {
e.printstacktrace();
}
}
private static double calculate(string expr) throws exception {
string classname = "calculatormain";
string methodname = "calculate";
string source = "class " + classname
+ " { public static void main(string[] args){system.out.println(calculate());} public static double " + methodname + "() { return "
+ expr + "; } }";
javacompiler compiler = toolprovider.getsystemjavacompiler();
standardjavafilemanager filemanager = compiler.getstandardfilemanager(
null, null, null);
stringsourcejavaobject sourceobject = new test.stringsourcejavaobject(
"main", source);
iterable<? extends javafileobject> fileobjects = arrays
.aslist(sourceobject);
compilationtask task = compiler.gettask(null, filemanager, null, null,
null, fileobjects);
boolean result = task.call();
if (result) {
classloader loader = thread.currentthread().getclass()
.getclassloader();
try {
class<?> clazz = loader.loadclass(classname);
method method = clazz.getmethod(methodname, new class<?>[] {});
object value = method.invoke(null, new object[] {});
return (double)value;
} catch (exception e) {
// throw new calculationexception("内部错误。");
}
} else {
// / new calculationexception("错误的表达式。");
}
return 0;
}
static class stringsourcejavaobject extends simplejavafileobject {
private string content = null;
public stringsourcejavaobject(string name, string content)
throws urisyntaxexception {
super(uri.create("string:///" + name.replace('.', '/')
+ kind.source.extension), kind.source);
this.content = content;
}
public charsequence getcharcontent(boolean ignoreencodingerrors)
throws ioexception {
return content;
}
}
}
上一篇: Android复选框对话框用法实例简析
下一篇: C#面向对象特征的具体实现及作用详解