给定类(class)
public class TestClass
{
private static List<TestClass> tmp = new ArrayList<>();
private String test1 = "";
private String test2 = "";
private String test3 = "";
}
我正在尝试定义一个自定义 IntelliJ
代码生成模板,它将在表单中创建一个 toString()
方法
public String toString()
{
final String output = "%s{ test1[%s], test2[%s], test3[%s] }";
return String.format(output, this.getClass().getSimpleName(), test1, test2, test3);
}
我有以下速度模板,但输出不正确。
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);
}
当我尝试向模板字符串添加右大括号 (}) 时,它无法呈现。
我也无法弄清楚如何删除每个字段及其值容器(方括号)之间的空格,也无法弄清楚如何在每个逗号后添加空格。我已经检查了 Apache Velocity 文档,但没有找到任何可以应用的内容。
我知道我可以使用StringBuilder
并将正确的元素组合在一起以获得相同的输出。然而,现在让 Velocity 模板使用上述格式工作是一个任务:-)
最佳答案
您可以使用 ${}
而不是 $
来访问变量,这将有助于处理空格:
final String output = "%s{ #foreach($member in $members)#if($i == 0)${member.accessor}[%s]#else, ${member.accessor}[%s]#end#set($i = $i + 1)#end ";
关于java - 用于生成自定义 IntelliJ toString 方法的 Velocity 模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52879991/