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;
}
Run Code Online (Sandbox Code Playgroud)
EMF 已经有自己的自省机制,不使用 Java 反射,而是使用静态生成的代码。
你需要的是这样的:
object.eSet(attribute, value);
Run Code Online (Sandbox Code Playgroud)
如果属性是“多”关系,比如 a List,则需要先检索列表,然后将内容添加到列表中:
if (attribute.isMany()) {
List<Object> list = (List<Object>) object.eGet(attribute);
list.addAll(value);
}
Run Code Online (Sandbox Code Playgroud)
如果您没有EAttribute但有属性名称(如String),您还可以EStructuralFeature使用EClass元数据按名称检索:
EStructuralFeature feature = object.eClass.getEStructuralFeature(attributeName);
object.eSet(feature, value);
Run Code Online (Sandbox Code Playgroud)
您应该查看 EObject API,特别是以“e”开头的方法。EcoreUtil类也有有用的方法。
| 归档时间: |
|
| 查看次数: |
607 次 |
| 最近记录: |