Java 了解EOObject及其EAttribute的设置值

Java 了解EOObject及其EAttribute的设置值,java,eclipse,emf,Java,Eclipse,Emf,我想设置对象EObject的值,知道它是EAttribute。可能吗 我可以使用反射、构建方法名并调用它,但是有更好的方法实现这一点吗?也许是一些EMF-Util类 public static Object invokeMethodBy(EObject object, EAttribute attribute, Object...inputParameters){ String attrName = attribute.getName().substring(0, 1).toUpperC

我想设置对象
EObject
的值,知道它是
EAttribute
。可能吗

我可以使用反射、构建方法名并调用它,但是有更好的方法实现这一点吗?也许是一些EMF-Util类

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

EMF已经有了自己的内省机制,它不使用Java反射,而是使用静态生成的代码

您需要的是:

object.eSet(attribute, value);
如果属性是“多”关系,例如
列表
,则需要在之前检索列表,然后将内容添加到列表中:

if (attribute.isMany()) {
    List<Object> list = (List<Object>) object.eGet(attribute);
    list.addAll(value);
}
您应该查看EObjectAPI,特别是以“e”开头的方法
EcoreUtil
类还有一些有用的方法

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