5

I have a Java method that is passed a String and an EMF EObject. The String is meant to be the name of an attribute of the EObject. For example, if it were passed "foo" and EObject eobj, it would need to access eobj.getFoo(). I know how to get the value of an EAttibute from its featureID, but can't seem to find a way to get it by attribute name. Is this even possible?

Leonide
  • 235
  • 3
  • 11

1 Answers1

4

The following should do the trick, but it is not elegant at all. It obtains the eClass of your eObject, finds a matching attribute definition by name and accesses it. The getEAllAttributes() used here also includes attributes defined by parent classes.

    EObject eObject = null;
    String attributeName = "";
    EDataType resultingDataType = null;
    EList<EAttribute> eAllAttributes = eObject.eClass().getEAllAttributes();
    for (EAttribute eAttribute : eAllAttributes) {
        if (eAttribute.getName().equals(attributeName)) {
            resultingDataType = (EDataType) eObject.eGet(eAttribute);
        }           
    }
    System.out.println(resultingDataType);
Lii
  • 11,553
  • 8
  • 64
  • 88
Jörn Guy Süß
  • 1,408
  • 11
  • 18
  • 7
    If you are sure that you'll get an attribute, just doing `eGet(eClass.getEStructuralFeature("foo"))` should be enough (and an assertion). – Volker Stolz Nov 14 '12 at 09:36