janino以及javacc是不错的选择,都是好多框架的选择
janino 参考使用
- pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.dalong</groupId>
<artifactId>javacapp</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.codehaus.janino</groupId>
<artifactId>janino</artifactId>
<version>3.1.3</version>
</dependency>
<dependency>
<groupId>me.nimavat</groupId>
<artifactId>shortid</artifactId>
<version>1.0.1.RC1</version>
</dependency>
</dependencies>
<repositories>
<repository>
<id>demo</id>
<url>http://dl.bintray.com/snimavat/maven</url>
</repository>
</repositories>
</project>
- main
package com.dalong;
import org.codehaus.commons.compiler.CompileException;
import org.codehaus.janino.ScriptEvaluator;
import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;
public class App {
static void method1(String item) {
System.out.printf(item);
}
public static void main(String[] args) throws CompileException, InvocationTargetException {
ScriptEvaluator se = new ScriptEvaluator();
se.cook(
""
+ "static void method1() {
"
+ " System.out.println(1);
"
+ "}
"
+ "
"
+ "method1();
"
+ "method2();
"
+ "
"
+ "static void method2() {
"
+ " System.out.println(me.nimavat.shortid.ShortId.generate().toString());
"
+ "}
"
);
Arrays.stream(se.getDefaultImports()).iterator().forEachRemaining(App::method1);
se.evaluate(new Object[0]);
}
}
javacc
javacc 的使用就有点复杂了,需要定义自己的schema 然后进行代码生成
- 下载jar
参考地址:https://javacc.github.io/javacc/ 注意下载jar 包,同时重命名为javacc.jar - 配置命令
javacc shell 同时添加执行权限
#!/bin/sh
java -classpath javacc.jar javacc "$@"
- 创建一个简单的schema
options {
STATIC = false;
}
PARSER_BEGIN(Adder)
import java.io.*;
class Adder {
public static void main(String[] args) {
for (String arg : args) {
try {
System.out.println(evaluate(arg));
} catch (ParseException ex) {
System.err.println(ex.getMessage());
}
}
}
public static long evaluate(String src) throws ParseException {
Reader reader = new StringReader(src);
return new Adder(reader).expr();
}
}
PARSER_END(Adder)
SKIP: { <[" ", " ", "
", "
"]> }
TOKEN: {
<INTEGER: (["0"-"9"])+>
}
long expr():
{
Token x, y;
}
{
x=<INTEGER> "+" y=<INTEGER> <EOF>
{
return Long.parseLong(x.image) + Long.parseLong(y.image);
}
}
- 生成代码
./javacc app.jj
- 效果
- 编译执行
javac Adder.java
java Adder 1+2
参考资料
https://github.com/javacc/javacc
https://github.com/janino-compiler/janino
https://github.com/apache/calcite/blob/master/core/src/main/codegen/templates/Parser.jj