Esempio n. 1
0
  @Override
  public void generate(JDefinedClass cls, GenerationContext context) {
    if (classSpec.getFields().isEmpty()) {
      return; // No equals needed.
    }

    // Import the objects class, for hash coding.
    JClass objects = context.getTypeManager().getClassDirect("java.util.Objects");

    // Create the equals method.
    JMethod hashMethod = cls.method(JMod.PUBLIC, int.class, "hashCode");
    hashMethod.annotate(Override.class);
    JBlock body = hashMethod.body();

    // Check if the object is null.
    JVar hash = body.decl(JType.parse(context.getCodeModel(), "int"), "hash", JExpr.lit(3));

    // Do check for each field.
    for (DataFieldSpecification fieldSpec : classSpec.getFields()) {
      List<String> parts = NameFormat.namesToList(fieldSpec.getFieldName());
      String camelCaseFieldName = NameFormat.camelCase(parts, false);
      // Get the field value.
      JExpression thisField = JExpr.refthis(camelCaseFieldName);
      // Accumulate the hash code.
      JExpression fieldHashCode = objects.staticInvoke("hashCode").arg(thisField);

      body.assign(hash, JExpr.lit(79).mul(hash).plus(fieldHashCode));
    }

    // Return the processed hash value.
    body._return(hash);
  }