Update equals() method code generation to use pattern matching
已回答
Is there a way to change the default template of java.util.Objects.equals and hashCode (java 7+) to use pattern matching every time it generates the code? As it stands right now, the IDE tells me that the code can be shortened by using pattern matching. I do not know how to reformat the code to create my own template.
请先登录再写评论。
Hello - could you describe what you would like to achieve in more detail using an example?
Certainly.
This is what the equals() method before pattern matching existed and what the IDE generates by default:
After pattern switching though and what I want the IDE to always use when generating equals method is:
You can change the default template - in the Generate popup, click equals() and hashCode(), then click to open the Templates dialog, where you can create a custom template based on a default one. Check https://www.jetbrains.com/help/idea/generating-code.html#customize-templates for the details
Yes but do you think you could directly tell me what the new code would look like? I think it would be a very small code change.
Kanishknishar
e.g. you can try this template:
#parse("equalsHelper.vm")public boolean equals(##
#if ($settings.generateFinalParameters)
final ##
#end
Object $paramName){
if(this == $paramName) return true;
if(!($paramName instanceof $classname ${classInstanceName})) return false;
#if ($superHasEquals)
if(!super.equals($paramName)) return false;
#end
return ##
#set($i = 0)
#foreach($field in $fields)
#if ($i > 0)
&& ##
#end
#set($i = $i + 1)
#if ($field.primitive)
#if ($field.double || $field.float)
#addDoubleFieldComparisonConditionDirect($field) ##
#else
#addPrimitiveFieldComparisonConditionDirect($field) ##
#end
#elseif ($field.enum)
#addPrimitiveFieldComparisonConditionDirect($field) ##
#elseif ($field.array)
java.util.Arrays.equals($field.accessor, ${classInstanceName}.$field.accessor)##
#elseif ($field.notNull)
${field.accessor}.equals(${classInstanceName}.$field.accessor)##
#else
java.util.Objects.equals($field.accessor, ${classInstanceName}.$field.accessor)##
#end
#end
;
}
It seems to work. Thanks a lot!
and just in case: you can see the following code in the original template in IDEA:
#parse("equalsHelper.vm")...
#addEqualsPrologue()
#addClassInstance()
This refers to https://github.com/JetBrains/intellij-community/blob/master/java/java-impl/src/com/intellij/codeInsight/generation/equalsHelper.vm, lines 26 and 4
You can use it as an example how you can modify the template