gpt4 book ai didi

java - 设置知道 EObject 及其 EAttribute 的值

转载 作者:行者123 更新时间:2023-11-30 08:22:43 24 4
gpt4 key购买 nike

我想设置对象 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 已经有自己的内省(introspection)机制,不使用 Java 反射,而是使用静态生成的代码。

你需要的是:

object.eSet(attribute, value);

如果属性是“多”关系,比如List,需要先获取列表,再往列表中添加内容:

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

如果您没有 EAttribute 但有属性名称(如 String),您还可以检索 EStructuralFeature使用 EClass 元数据按名称:

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

您应该查看 EObject API,特别是以“e”开头的方法。 EcoreUtil 类也有一些有用的方法。

关于java - 设置知道 EObject 及其 EAttribute 的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24179668/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com