You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何避免StreamingTemplateEngine缺失Map参数时抛出MissingPropertyException并替换为null

解决Groovy StreamingTemplateEngine缺失参数时抛出MissingPropertyException的问题

默认情况下,用StreamingTemplateEngine渲染模板时,如果模板里的变量在绑定的Map中找不到,Groovy会直接抛出MissingPropertyException。要避免这个问题并把缺失的变量替换成null,你可以通过自定义绑定逻辑或者利用Groovy的动态特性来实现,下面是两种实用的方法:

方法一:自定义SafeBinding类

最稳妥的方式是继承Groovy自带的Binding类,重写它的getProperty方法,让它在变量不存在时返回null而不是抛出异常:

import groovy.text.StreamingTemplateEngine
import groovy.text.Template

class Test {
    private static Writable binding(Map map, String string) {
        Template template = new StreamingTemplateEngine().createTemplate(string)
        // 用自定义的SafeBinding包装传入的Map
        return template.make(new SafeBinding(map))
    }

    static void main(String... args) {
        def template = "\${test1} \${test2}"
        def map = ["test1": "test1"]
        print binding(map, template) // 输出结果:test1 null
    }
}

// 自定义绑定类,处理缺失的变量
class SafeBinding extends groovy.lang.Binding {
    SafeBinding(Map map) {
        super(map)
    }

    @Override
    Object getProperty(String property) {
        // 先检查变量是否存在,不存在则返回null
        return super.hasVariable(property) ? super.getProperty(property) : null
    }
}

这个方法的好处是扩展性强——如果你之后想把缺失的变量替换成空字符串或者其他默认值,只需要修改getProperty方法的返回值即可。

方法二:利用Expando动态类

如果你想要更简洁的实现,可以用Groovy内置的Expando类。Expando是一个动态对象,当访问它不存在的属性时会自动返回null,完美契合我们的需求:

import groovy.text.StreamingTemplateEngine
import groovy.text.Template

class Test {
    private static Writable binding(Map map, String string) {
        Template template = new StreamingTemplateEngine().createTemplate(string)
        def expando = new Expando()
        // 将Map中的属性赋值给Expando
        expando.properties = map
        return template.make(expando)
    }

    static void main(String... args) {
        def template = "\${test1} \${test2}"
        def map = ["test1": "test1"]
        print binding(map, template) // 输出结果:test1 null
    }
}

这种写法不需要额外定义类,代码更紧凑,适合简单场景。

两种方法都能有效避免MissingPropertyException,并把缺失的变量替换为null,你可以根据自己的需求选择合适的方案。

内容的提问来源于stack exchange,提问作者Simkin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 09:41:11