用于生成自定义IntelliJ toString方法的Velocity模板 [英] Velocity Template for generating custom IntelliJ toString method

查看:121
本文介绍了用于生成自定义IntelliJ toString方法的Velocity模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给班上

public class TestClass
{
    private static List<TestClass> tmp = new ArrayList<>();

    private String test1 = "";
    private String test2 = "";
    private String test3 = "";
}

我正在尝试定义一个自定义的IntelliJ代码生成模板,该模板将创建以下形式的toString()方法

I'm trying to define a custom IntelliJ code generation template that will create a toString() method in the form

public String toString()
{
    final String output = "%s{ test1[%s], test2[%s], test3[%s] }";

    return String.format(output, this.getClass().getSimpleName(), test1, test2, test3);
}

我有以下速度模板,但输出不正确.

I have the following velocity template but the output is not correct.

public java.lang.String toString() 
{
#set($i = 0)
final String output = "%s{ #foreach($member in $members)#if($i == 0)$member.accessor [%s]#else,$member.accessor [%s]#end#set($i = $i + 1)#end ";

return String.format(output, this.getClass().getSimpleName() #foreach($member in $members),$member.accessor #end); 
}

输出为

public String toString()
{
    final String output = "%s{ test1 [%s],test2 [%s],test3 [%s] ";

    return String.format(output, this.getClass().getSimpleName(), test1, test2, test3);
}

当我尝试在字符串字符串中添加右括号(})时,模板将无法呈现.

When I attempt to add a closing brace (}) to the string the template- it fails to render.

我也无法弄清楚如何删除每个字段与其值容器(方括号)之间的空格,也无法弄清楚如何在每个逗号后添加空格.我检查了Apache Velocity文档,但没有找到我可以应用的任何内容.

I also cannot figure out how to remove the space between each field and its value container (the square brackets), nor can I figure out how to add a space after each comma. I have checked the Apache velocity documentation but haven't found anything that I can apply.

我知道我可以使用StringBuilder并将正确的元素拼凑在一起以获得相同的输出.但是,现在让Velocity模板使用上述格式工作是一项任务:-)

I know I could use StringBuilder and piece the correct elements together to get the same output. However, now getting the Velocity template to work using the above format is a quest :-)

推荐答案

您可以使用${}而不是$来访问变量,它将对空格有所帮助:

You can use ${} instead of $ for accessing variables, and it will help with the spaces:

final String output = "%s{ #foreach($member in $members)#if($i == 0)${member.accessor}[%s]#else, ${member.accessor}[%s]#end#set($i = $i + 1)#end ";

这篇关于用于生成自定义IntelliJ toString方法的Velocity模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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