0
votes

I am using EMF to generate Java classes from an ecore XML file. I am trying to, in this generated code, override the equals() and hashCode() methods, but I have not found any good guides online on how to generate anything beyond basic get and set methods. My sample.ecore file looks something like this:

<?xml version="1.0" encoding="UTF-8"?>
<ecore:EPackage xmi:version="2.0" xmlns:xmi="http://www.omg.org/XMI" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ecore="http://www.eclipse.org/emf/2002/Ecore" name="sample" nsURI="jewel:/sample" nsPrefix="sample">
    <eSubpackages name="models" nsURI="jewel:/sample.models" nsPrefix="models">
        <eClassifiers xsi:type="ecore:EClass" name="Foo" abstract="true" eSuperTypes="models.ecore#//Foo">
            <eStructuralFeatures xsi:type="ecore:EAttribute" name="code" eType="ecore:EDataType http://www.eclipse.org/emf/2002/Ecore#//EString"/>
            <eStructuralFeatures xsi:type="ecore:EAttribute" name="anotherAttribute" eType="ecore:EDataType http://www.eclipse.org/emf/2002/Ecore#//EString"/>
            <eStructuralFeatures xsi:type="ecore:EAttribute" name="aDateAttribute" eType="ecore:EDataType http://www.eclipse.org/emf/2002/Ecore#//EDate"/>
            <eStructuralFeatures xsi:type="ecore:EAttribute" name="aBooleanAttribute" eType="ecore:EDataType http://www.eclipse.org/emf/2002/Ecore#//EBoolean"/>
        </eClassifiers>
    </eSubpackages>
</ecore:EPackage>

I am trying to generate code that looks something like the below basic code:

@Override
public boolean equals(Object o) {
    if(o == this) return true;
    if(!(o instanceof Foo))
        return false;
    Foo foo = (Foo) o;
    return foo.code=code;
}

@Override
public int hashCode() {
    int result = 17;
    result = 31 * result + code.hashCode();
    return result;
}

Is there some kind of additional tag I can write inside of eClassifiers to generate this, or some kind of property that I need to change in the code generation?

1

1 Answers

0
votes

This should be possible by annotating an EOperation with the body keyword and the source code. The "http://www.eclipse.org/emf/2002/GenModel" annotations are picked up by the generator model.

<eOperations name="hash" eType="#//EInt"> 
      <eAnnotations source=" http://www.eclipse.org/emf/2002/GenModel "> 
        <details key=" body " value="int result = 17;&#xA;    result = 31 * result + code.hashCode();&#xA;    return result;"/> 
      </eAnnotations> 
 </eOperations>