@@ -154,21 +154,30 @@ private void implementEquals(JRecordType type, JMethod method, SourceInfo info)
154
154
JMethodBody body = new JMethodBody (info );
155
155
JParameter otherParam = method .getParams ().get (0 );
156
156
157
- // Equals is built from first == check between this and other, as a fast path for the same
158
- // object and also to ensure that other isn't null. Then MyRecord.class == other.getClass(),
159
- // and now we know they're the same type and can cast safely to access fields for the rest.
157
+ // if (this == other) return true;
160
158
JBinaryOperation eq =
161
159
new JBinaryOperation (info , JPrimitiveType .BOOLEAN , JBinaryOperator .EQ ,
162
160
new JThisRef (info , type ),
163
161
otherParam .createRef (info ));
164
162
body .getBlock ().addStmt (new JIfStatement (info , eq ,
165
163
JBooleanLiteral .TRUE .makeReturnStatement (), null ));
166
164
165
+ // other == null
166
+ JBinaryOperation nonNullCheck =
167
+ new JBinaryOperation (info , JPrimitiveType .BOOLEAN , JBinaryOperator .EQ ,
168
+ otherParam .createRef (info ), JNullLiteral .INSTANCE );
169
+ // MyRecordType.class != other.getClass()
167
170
JBinaryOperation sameTypeCheck =
168
171
new JBinaryOperation (info , JPrimitiveType .BOOLEAN , JBinaryOperator .NEQ ,
169
172
new JClassLiteral (info , type ),
170
173
new JMethodCall (info , otherParam .createRef (info ), getClassMethod ));
171
- body .getBlock ().addStmt (new JIfStatement (info , sameTypeCheck ,
174
+ // other == null || MyRecordType.class != other.getClass()
175
+ JBinaryOperation nullAndTypeCheck =
176
+ new JBinaryOperation (info , JPrimitiveType .BOOLEAN , JBinaryOperator .OR ,
177
+ nonNullCheck , sameTypeCheck );
178
+
179
+ // if (other == null || MyRecordType.class != other.getClass()) return false;
180
+ body .getBlock ().addStmt (new JIfStatement (info , nullAndTypeCheck ,
172
181
JBooleanLiteral .FALSE .makeReturnStatement (), null ));
173
182
174
183
// Create a local to assign to and compare each component
0 commit comments