【问题标题】:Generate method returning EMF Unmodifiable list生成返回 EMF 不可修改列表的方法
【发布时间】:2010-11-02 09:45:51
【问题描述】:

我通过如下注释的 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 文件以告诉生成器生成返回不可修改列表的代码? (谷歌搜索后我找不到...)

你如何处理这种情况?

提前致谢

手动

【问题讨论】:

    标签: java eclipse-emf


    【解决方案1】:

    您需要将生成的“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 的全部功能,而不仅仅是添加/删除您提供的)。

    【讨论】:

      猜你喜欢
      • 2011-04-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-23
      • 1970-01-01
      • 1970-01-01
      • 2011-10-27
      相关资源
      最近更新 更多