Velocity Template for generating custom IntelliJ toString method

只愿长相守 提交于 2019-12-12 19:19:41

问题


Given the class

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

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

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); 
}

The output is

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.

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.

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 :-)


回答1:


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 ";


来源:https://stackoverflow.com/questions/52879991/velocity-template-for-generating-custom-intellij-tostring-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!