Intellij模板生成器语法

3
在Intellij IDE中,您可以编写自己的代码生成模板。我想编写一个用于生成我的等于方法(equals method)的模板。 目标是拥有一个不区分null和空字符串的等于方法,像这样:
(使用apache.commons.language中的StringUtils.IsNotEmpty)
public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;

    POJO pojo = (POJO) o;

    if(StringUtils.IsNotEmpty(stringAtt) ? !stringAtt.equals(pojo.stringAtt) : StringUtils.IsNotEmpty(pojo.stringAtt)) return false;

    return true;       
}

我希望能将这个等式写成模板,以便为我使用的所有POJO生成代码。
问题在于,我并不完全理解用于IntelliJ模板生成的语言和标记的语法。它看起来像这样:
#parse("equalsHelper.vm")
public boolean equals(##
#if ($settings.generateFinalParameters)
  final ##
#end
Object $paramName){
#addEqualsPrologue()
#if ($fields.size() > 0)
  #addClassInstance()
#foreach($field in $fields)     
  #addFieldComparison($field)
#end
#end

return true;
}
##
#macro(addFieldComparison $field)
  #if ($field.notNull)
    if(!${field.accessor}.equals(${classInstanceName}.$field.accessor))return false;
  #else
    if($field.accessor != null ? !${field.accessor}.equals(${classInstanceName}.$field.accessor) : ${classInstanceName}.$field.accessor != null)return false;
  #end
#end
##

我在Intellij的文档页面上寻找了这个语法的解释,但没有找到。

  • 请问有人能给我一个好的例子或者指向一些文档网页,以便我学习如何使用它吗?
  • 或者请问这是哪种语言,我可以自己学习吗?

谢谢。


好问题。在这里看一下:https://www.jetbrains.com/help/idea/file-and-code-templates.html - Tim Biegeleisen
谢谢@TimBiegeleisen,我在文档中没有注意到。这种语言是VTL。 - alvaro
1个回答

2

因此,用于此操作的语言是Velocity模板语言(VTL)。

我想我的工作完成了。唯一重要的事情是检查POJO的字段是否为字符串。然后,如果是,则编写直接的代码。这是我的答案,希望能够帮助您。我只提供addFieldComparisson宏的代码,其余部分相同:

#macro(addFieldComparison $field)
  ## Check if the field is a String
  // CHECKED TYPE: ${field.accessor.class.name}
  #if (${field.accessor.class.name} == "java.lang.String")
    //is a String
    if(StringUtils.isNotEmpty($field.accessor) ? !${field.accessor}.equals(${classInstanceName}.$field.accessor) : StringUtils.isNotEmpty(${classInstanceName}.$field.accessor))return false;
  #else
    // Not a String
    if($field.accessor != null ? !${field.accessor}.equals(${classInstanceName}.$field.accessor) : ${classInstanceName}.$field.accessor != null)return false;
  #end
#end

我的Intellij Community 2017.2.5无法正常工作。所有的对象都被视为字符串。例如,${field.accessor.class.name}在所有字段中都返回java.lang.String,我已经仔细检查了其他类型的对象是否被传递给该方法,例如Java.Util.Date。我认为这是IDE的一个错误。有人知道吗? - alvaro

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接