Reputation: 462
In Intellij IDE you can writte your own templates for generating code. I would like to writte a template for generating my equals method.
The goal is to have a equals method that do not distiguish between null and a empty string like this:
(using StringUtils.IsNotEmpty from apache.commons.language)
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
POJO pojo = (POJO) o;
if(StringUtils.IsNotEmpty(stringAtt) ? !stringAtt.equals(pojo.stringAtt) : StringUtils.IsNotEmpty(pojo.stringAtt)) return false;
return true;
}
I would like to writte this equals as a template so I can generate code for all the POJOs I am using.
The problem is that I do not fully understand the syntax of language and tokens used for intellij template generation. It looks like this:
#parse("equalsHelper.vm")
public boolean equals(##
#if ($settings.generateFinalParameters)
final ##
#end
Object $paramName){
#addEqualsPrologue()
#if ($fields.size() > 0)
#addClassInstance()
#foreach($field in $fields)
#addFieldComparison($field)
#end
#end
return true;
}
##
#macro(addFieldComparison $field)
#if ($field.notNull)
if(!${field.accessor}.equals(${classInstanceName}.$field.accessor))return false;
#else
if($field.accessor != null ? !${field.accessor}.equals(${classInstanceName}.$field.accessor) : ${classInstanceName}.$field.accessor != null)return false;
#end
#end
##
I have looked for it on Intellij doc pages but I cant find a explanation for the syntax.
Thanks.
Upvotes: 3
Views: 713
Reputation: 462
So the language used for this is Velocity Template Language or VTL
I think I have the job done. The only important thing was to check if the POJO´s field is a String. Then if it is writte the code straigth foward. This is my answer I hope it helps, I´m only giving the code for the addFieldComparisson macro, the rest is the same:
#macro(addFieldComparison $field)
## Check if the field is a String
// CHECKED TYPE: ${field.accessor.class.name}
#if (${field.accessor.class.name} == "java.lang.String")
//is a String
if(StringUtils.isNotEmpty($field.accessor) ? !${field.accessor}.equals(${classInstanceName}.$field.accessor) : StringUtils.isNotEmpty(${classInstanceName}.$field.accessor))return false;
#else
// Not a String
if($field.accessor != null ? !${field.accessor}.equals(${classInstanceName}.$field.accessor) : ${classInstanceName}.$field.accessor != null)return false;
#end
#end
Upvotes: 2