繁体   English   中英

生成返回EMF不可修改列表的方法

[英]Generate method returning EMF Unmodifiable list

我正在通过带注释的Java代码使用EMF,如下所示

/**
 * Adds the given type to this filter. Has no effect if the given type
 * already belongs to this filter.
 * 
 * @param type
 *            the type to add
 * @model
 */
public void addEntityType(String type);

/**
 * Returns the list of types belonging to this filter. Types are identified
 * by there name.
 * 
 * @return the list of types for this entity type filter
 * 
 * @model
 */
public List<String> getEntityTypes();

/**
 * Removes the given type from this filter. Has no effect if the given type
 * doesn't belong to this filter.
 * 
 * @param type
 *            the type to remove
 * @model
 */
public void removeEntityType(String type);

从该带注释的接口创建ecore和genmodel文件之后,并在生成代码后,对getEntityTypes方法进行如下修改:

public EList<String> getEntityTypes();

出于封装目的,我希望此EList不可修改,因此接口客户端的代码只能通过add和remove方法修改列表。

有什么干净的方法可以修改Java批注或genmodel文件,以通知生成器生成返回不可修改列表的代码? (在谷歌搜索后我找不到它了……)

您如何处理这种情况?

提前致谢

马努

您将需要修改生成的“ Impl”类,使其看起来像这样:

/**
 * <!-- begin-user-doc -->
 * <!-- end-user-doc -->
 * @generated
 */
private EList<String> getEntityTypesGen() {
    if (entityTypes == null) {
        entityTypes = new EDataTypeUniqueEList<String>(String.class, 
            this, NsPackage.THINGY__ENTITY_TYPES);
    }
    return entityTypes;
}

public EList<String> getEntityTypes() {
    return ECollections.unmodifiableEList(getEntityTypesGen());
}

/**
 * <!-- begin-user-doc -->
 * <!-- end-user-doc -->
 * @generated NOT
 */
public void addEntityType(String type) {
    getEntityTypesGen().add(type);
}

/**
 * <!-- begin-user-doc -->
 * <!-- end-user-doc -->
 * @generated NOT
 */
public void removeEntityType(String type) {
    getEntityTypesGen().remove(type);
}

请注意,我已完成以下操作:

  1. 将生成的getEntityTypes方法的名称和可见性分别更改为getEntityTypesGen和private。 EMF在重新生成此方法时不会影响可见性。 同样,即使我们现在有一个未生成的getEntityTypes方法,EMF仍将继续生成此“ Gen”后缀的方法。
  2. 添加了一个公共的,未生成的getEntityTypes方法,该方法将默认实现的结果包装在不可修改的EList中。
  3. 通过委派给生成的getEntityTypesGen方法(其结果仍可修改)来实现(并更改为未生成)add / removeEntityType方法。

不过,就我个人而言,我不推荐这种方法。 EMF通常返回多值引用的可修改列表,客户应该修改这些值以添加或删除项目。 EMF将根据需要懒惰地创建一个空列表,因此它使界面更简洁(不需要添加/删除方法)和一个不错的API(用户可以轻松使用列表API的全部功能,而不仅仅是添加/删除)您提供的)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM