Groovy自定義函數實現時間表達式解析


class RecScript extends Script {
    @Override
    Object run() {
        return null
    }

    static Object addYear(String str, int num){
        def (localDate, formatter) = formatLocalTate(str)
        def months = localDate.plusYears(num)
        return formatter.format(months)
    }
    static Object addMonth(String str, int num){
        def (localDate, formatter) = formatLocalTate(str)
        def months = localDate.plusMonths(num)
        return formatter.format(months)
    }
    static Object addDay(String str, int num){
        def (localDate, formatter) = formatLocalTate(str)
        def months = localDate.plusDays(num)
        return formatter.format(months)
    }
    private static List formatLocalTate(String str) {
        def formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss")
        def localDate = LocalDateTime.parse(str, formatter)
        [localDate, formatter]
    }

}

  

class RecTimeSupport {

    private static final Object lock = new Object()
    private static final GroovyShell shell
    private static HashMap<String, Script> cache = new HashMap<String, Script>()
    static {
        CompilerConfiguration cfg = new CompilerConfiguration()
        cfg.setScriptBaseClass(RecScript.class.getName())

        shell = new GroovyShell(cfg)
    }

    static Object parseExpr(String expr) {
        Script s = getScriptFromCache(expr)
        return s.run()
    }

    static Object parseExpr(String expr, Map<?, ?> map) {
        Binding binding = new Binding(map)
        Script script = getScriptFromCache(expr)
        script.setBinding(binding)
        return script.run()
    }
    private static Script getScriptFromCache(String expr) {
        if (cache.containsKey(expr)) {
            return cache.get(expr)
        }
        synchronized (lock) {
            if (cache.containsKey(expr)) {
                return cache.get(expr)
            }
            Script script = shell.parse(expr)
            cache.put(expr, script)
            return script
        }
    }

    static void main(String[] args) {
        def str = "ORDER_TIME == addMonth(ACT_TIME,2)"
        def map = [:]
        map.'ORDER_TIME' = '20190613121212'
        map.'ACT_TIME' = '20190413121212'

        // 綁定參數實例
        println parseExpr(str,map)
        // 未綁定參數
        println parseExpr("3+4")

    }
}


一個腳本總是編譯成class。Groovy編譯器將為您編譯該類,並將腳本主體復制到run方法中

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM