I am attempting to generate Java Value Objects using com.sun.codemodel.JCodeModel
.
I have managed to generate hashcode()
and equals()
methods but I am struggling with toString()
;
I require the following toString()
implementation
return "ClassName [field1 = " + field1 + ", field2 = " + field2 ... ", fieldN = " + fieldN + "]";
How do I create a JCodeModel
JExpression
that contains JExpr.lit(field1.name())
concatenated with JExpr.ref(fieldVar.name())
?
All i've managed to do is generate a string literal resembling:-
return "ClassName [field1 = field1 + field2 = field2 ... fieldN = + fieldN + ]";
Heres my skeleton method so far:-
final Map<String, JFieldVar> fields = jclass.fields();
final JMethod toString = jclass.method(JMod.PUBLIC, String.class, "toString");
final Set<String> excludes = new HashSet<String>(Arrays.asList(ruleFactory.getGenerationConfig().getToStringExcludes()));
final JBlock body = toString.body();
for (JFieldVar fieldVar : fields.values()) {
if (excludes.contains(fieldVar.name()) || ((fieldVar.mods().getValue() & JMod.STATIC) == JMod.STATIC)) {
continue;
}
??????????????
}
body._return(?????????);
toString.annotate(Override.class);
The key point here is likely that you can combine multiple
JExpression
objects with the+
operator by using theJExpression#plus
method.Here is an example that contains the definition of a simple example class, and a method to generically generate the
toString
method:The generated class with the
toString
method is shown here:The fact that CodeModel inserts
(
brackets)
around each binary operation causes the code to not look so pretty. But it's understandable: Otherwise, they would have to take operator precedences into account, and the usage and the code generation itself would likely be far harder.However, the result of this
toString
method will bewhich should be what you expected, based on your examples.