使用Janino計算Java表達式

官方介紹

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章