Java 将字符串动态生成字节码的实现方法
Java 将字符串动态生成字节码的实现方法
发布时间:2016-12-28 来源:查字典编辑
摘要:可以生成可执行的class文件直接上能执行代码:复制代码代码如下:publicclassTest{/***@paramargs*/@Supp...

可以生成可执行的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;

}

}

}

推荐文章
猜你喜欢
附近的人在看
推荐阅读
拓展阅读
相关阅读
网友关注
最新Java学习
热门Java学习
编程开发子分类