簡體   English   中英

使用 GroovyShell.evaluate 時跳過 MissingPropertyException

[英]Skip MissingPropertyException while using GroovyShell.evaluate

有沒有辦法跳過MissingPropertyException同時使用GroovyShell.evaluate

def sharedData = new Binding()
def shell = new GroovyShell(sharedData)
shell.evaluate("a=5; b=1") // works fine

// How to not get MissingPropertyException, or silently ignore property 'a'
shell.evaluate("a; b=1") // MissingPropertyException for 'a'

我知道 Expando 解決方案,有沒有辦法在不定義類的情況下做到這一點?

一個非常簡單的方法是覆蓋Binding.getVariable 請注意,這是非常直接的:“所有異常”都被忽略——您可能希望有更好的日志記錄或更准確的錯誤處理。

import groovy.lang.*

class NoOpBinding extends Binding {
    @Override
    Object getVariable(String name) {
        try {
            return super.getVariable(name)
        }
        catch (Throwable t) {
            println "Ignoring variable=`$name`"
            return null
        }
    }
}

def shell = new GroovyShell(new NoOpBinding())
shell.evaluate("a; b=1") // MissingPropertyException for 'a'
// → Ignoring variable=`a`
println shell.getVariable('b')
// → 1

你可以這樣做:

def binding = [:].withDefault { }
def shell = new GroovyShell(binding as Binding)

shell.evaluate 'a; b=1'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM