aphex aphex - 3 months ago 6
Java Question

Set value knowing the EObject and its EAttribute

I want to set the value of an object

EObject
knowing it's
EAttribute
. Is that possible?

I can use reflections, build the method name and invoke it, but is there a better way to achieve that? Maybe some EMF Util classes?

public static Object invokeMethodBy(EObject object, EAttribute attribute, Object...inputParameters){
String attrName = attribute.getName().substring(0, 1).toUpperCase() + attribute.getName().substring(1);
Object returnValue = null;
try {
returnValue = object.getClass().getMethod("set"+attrName, boolean.class).invoke(object,inputParameters);
} catch (IllegalAccessException | IllegalArgumentException
| InvocationTargetException | NoSuchMethodException
| SecurityException e1) {
e1.printStackTrace();
}
return returnValue;
}

Answer

EMF has already its own introspection mechanisms, that do not use Java Reflection but use static generated code.

What you need is this:

object.eSet(attribute, value);

If the attribute is a "many" relationship, such as a List, you need to retrieve the list before and then add the content to the list:

if (attribute.isMany()) {
    List<Object> list = (List<Object>) object.eGet(attribute);
    list.addAll(value);
}

In case you don't have the EAttribute but have the name of the attribute (as String) you can also retrieve the EStructuralFeature by name using the EClass metadata:

EStructuralFeature feature = object.eClass.getEStructuralFeature(attributeName);
object.eSet(feature, value);

You should look to the EObject API, in special the methods starting by "e". EcoreUtil class has also useful methods.