这里的关键点很可能是你可以通过使用该方法将多个JExpression
对象与运算符组合起来。+
JExpression#plus
这是一个示例,其中包含一个简单示例类的定义,以及一个通用生成该方法的toString
方法:
import java.util.Arrays;
import java.util.Collection;
import java.util.Map;
import com.sun.codemodel.CodeWriter;
import com.sun.codemodel.JBlock;
import com.sun.codemodel.JCodeModel;
import com.sun.codemodel.JDefinedClass;
import com.sun.codemodel.JExpr;
import com.sun.codemodel.JExpression;
import com.sun.codemodel.JFieldVar;
import com.sun.codemodel.JMethod;
import com.sun.codemodel.JMod;
import com.sun.codemodel.writer.SingleStreamCodeWriter;
public class CodeModelToStringTest
{
public static void main(String[] args) throws Exception
{
JCodeModel codeModel = new JCodeModel();
JDefinedClass definedClass = codeModel._class("com.example.Example");
definedClass.field(JMod.PUBLIC, String.class, "exampleString");
definedClass.field(JMod.PROTECTED, int.class, "exampleInt");
definedClass.field(JMod.PRIVATE, float.class, "exampleFloat");
definedClass.field(JMod.PRIVATE, String.class, "excludedString");
definedClass.field(JMod.STATIC, String.class, "staticString");
createToStringMethod(definedClass, Arrays.asList("excludedString"));
CodeWriter codeWriter = new SingleStreamCodeWriter(System.out);
codeModel.build(codeWriter);
}
private static void createToStringMethod(
JDefinedClass definedClass,
Collection<String> excludedFieldNames)
{
Map<String, JFieldVar> fields = definedClass.fields();
JMethod toString =
definedClass.method(JMod.PUBLIC, String.class, "toString");
toString.annotate(Override.class);
JBlock body = toString.body();
JExpression expression = JExpr.lit(definedClass.name() + " [");
boolean first = true;
for (JFieldVar fieldVar : fields.values())
{
if ((fieldVar.mods().getValue() & JMod.STATIC) == JMod.STATIC)
{
continue;
}
if (excludedFieldNames.contains(fieldVar.name()))
{
continue;
}
if (!first)
{
expression = expression.plus(JExpr.lit(", "));
}
expression = expression.plus(JExpr.lit(fieldVar.name()+" = "));
expression = expression.plus(JExpr.ref(fieldVar.name()));
first = false;
}
expression = expression.plus(JExpr.lit("]"));
body._return(expression);
}
}
使用该toString
方法生成的类如下所示:
package com.example;
public class Example {
public String exampleString;
protected int exampleInt;
private float exampleFloat;
private String excludedString;
static String staticString;
@Override
public String toString() {
return ((((((((("Example ["+"exampleString = ")+ exampleString)+", ")+"exampleInt = ")+ exampleInt)+", ")+"exampleFloat = ")+ exampleFloat)+"]");
}
}
(
CodeModel 在每个二进制操作周围插入括号的事实)
导致代码看起来不那么漂亮。但这是可以理解的:否则,他们将不得不考虑运算符的优先级,并且使用和代码生成本身可能会更加困难。
但是,此toString
方法的结果将是
Example [exampleString = null, exampleInt = 0, exampleFloat = 0.0]
根据您的示例,这应该是您所期望的。