官方介绍
Janino是一个超小型,超快的Java编译器。
Janino不仅可以将一组源文件编译为一组类文件(如JAVAC),还可以在内存中编译Java表达式,块,类主体或源文件,加载字节码并直接在同一JVM中执行。
JANINO与Apache Commons JCI(“Java编译器接口”)和JBoss Rules / Drools集成在一起。
JANINO还可用于 静态代码分析 或 代码修改。
代码示例
修改了下官方的示例代码
import org.codehaus.commons.compiler.CompilerFactoryFactory;
import org.codehaus.commons.compiler.IExpressionEvaluator;
import org.springframework.util.StopWatch;
/**
* Sample application which demonstrates how to use the {@link IExpressionEvaluator} class.
*/
public class ShippingCost {
public static void main(String[] args) throws Exception {
//StopWatch 计算方法耗时的优雅方式,这里使用的是spring的,guava和apach-commons都有类似的功能
StopWatch sw = new StopWatch();
// Convert command line argument to call argument "total".
Object[] arguments = {new Double(120), new Integer(10)};
sw.start("实例化表达式解析器");
// Create "ExpressionEvaluator" object.
IExpressionEvaluator ee = CompilerFactoryFactory.getDefaultCompilerFactory().newExpressionEvaluator();
sw.stop();
ee.setExpressionType(boolean.class);
ee.setParameters(new String[]{"total", "count"}, new Class[]{double.class, int.class});
sw.start("设置表达式");
ee.cook("count == 10 || total >= 100.0 && count > 8");
sw.stop();
sw.start("计算表达式");
// Evaluate expression with actual parameter values.
Object res = ee.evaluate(arguments);
sw.stop();
// Print expression result.
System.out.println("Result = " + res);
System.out.println(sw.prettyPrint());
System.out.println(sw.shortSummary());
}
}
PS
logback Conditional processing 就使用了Janino库来提升性能
https://logback.qos.ch/manual/configuration.html#conditional
还有很多用处,详见官网http://janino-compiler.github.io/janino/及GitHub地址https://github.com/janino-compiler/janino