2009-06-12 45 views
2

我使用EMF通过注释的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是不可修改的,因此接口客户端的代码只能通过添加和删除方法来修改列表。

是否有任何干净的方式来做到这一点,即修改Java注释或genmodel文件以告诉生成器生成返回不可修改列表的代码? (Google搜寻后我无法找到...)

你如何管理这种情况?

在此先感谢

马努

回答

4

你会需要修改生成的 “默认地将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(用户可以轻松掌握list API的全部功能,而不仅仅是添加/删除你提供)。