问题
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