参数匹配Java类名的Groovy模板引擎 [英] Groovy template engine with parameters matching a Java class name

查看:426
本文介绍了参数匹配Java类名的Groovy模板引擎的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我确信这是一个简单的...

我们使用Groovy模板引擎将XML文档格式化为可读格式。代码扫描XML并为XML中的每个项目创建一个条目,然后将其传递给Groovy模板引擎。

当XML包含一个与类名相匹配的属性 -
时,会出现这样的问题:< Date> some date< /日期和GT; 。如果模板文件指定 Date为$ Date (例如),而不是实际的日期字符串,我们得到类java.util.Date 。我们尝试过 $ Date 类似 $ {Date} $ {Date。 toString()} 等没有运气。



我们认为问题在于Groovy会混淆Date输入变量和java.util.Date类,但我确信有某种语法会使这个工作正常。由于我们通过这个提供了任意用户定义的XML,所以我们实际上无法控制像XML中的属性名称这样的东西。



以下是复制问题的几行代码:

  def map = [:] 
map.putAt(Date,new Date())//失败
map.putAt(Date2,new Date())// Works
def tf = new File(Test.template)
def gte = new GStringTemplateEngine()
def tpl = gte.createTemplate(tf).make(map.withDefault {null})
println tpl.toString()

Test.template文件包含:

 日期为$ {Date.toString()}。 
日期是$ {Date2.toString()}。

我们得到的结果是:

  Date是类java.util.Date。 
日期为星期二06六月20:22:16 EDT。


解决方案

在这里回答我自己的问题,以防别人有类似的问题。

我们发现GroovygetVariable()方法是一种适用于我们的解决方案。 getVariable()方法返回任何变量的值,并且它暴露在模板引擎中。在上面的示例中更改模板为:

  Date是$ {getVariable(Date)} 

解决了我们的问题。

I'm sure this is a simple one...

We use the Groovy template engine to format XML documents into human-readable form. The code scans the XML and creates a map with an entry for each item in the XML, and then this is passed to the Groovy template engine.

Problem occurs when the XML contains an attribute that matches a class name - something like this: <Date>some date</Date>. If the template file specifies Date is $Date (for example), instead of the actual date string, we're getting class java.util.Date. We've tried variations on $Date like ${Date} and ${Date.toString()}, etc with no luck.

We think the issue is that Groovy confuses Date the input variable, and the java.util.Date class, but I'm sure there's some sort of syntax that will make this work properly. Since we feed arbitrary user-defined XML through this, we really can't control things like the attribute names in the XML.

Here's a few lines of code to replicate the problem:

def map = [:]
map.putAt("Date",  new Date())  // Fails
map.putAt("Date2", new Date())  // Works
def tf = new File("Test.template")
def gte = new GStringTemplateEngine()
def tpl = gte.createTemplate(tf).make(map.withDefault{null})
println tpl.toString()

The "Test.template" file contains:

Date is ${Date.toString()}.
Date is ${Date2.toString()}.

The output we get is:

Date is class java.util.Date.
Date is Tue Jun 06 20:22:16 EDT 2017.

解决方案

Answering my own question here, just in case someone else has a similar problem.

We found that the Groovy "getVariable()" method is a solution that works for us. The getVariable() method returns the value of any variable, and it's exposed inside the template engine. Changing the template to in my example above to:

Date is ${getVariable("Date")}

Solved the problem for us.

这篇关于参数匹配Java类名的Groovy模板引擎的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆