Eclipse EMF: How to get access EAttribute by name?

2019-07-06 12:12发布

问题:

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?

回答1:

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);