Home > Articles > Programming > Java

Introducing EMF

This chapter is from the book

2.5 The Runtime Framework

In addition to simply increasing your productivity, building your application using EMF provides several other benefits, such as model change notification, persistence support including default XMI serialization, and an efficient reflective API for manipulating EMF objects generically. Most importantly, EMF provides the foundation for interoperability with other EMF-based tools and applications.

2.5.1 Notification and Adapters

In Section 2.4.1, we saw that every generated EMF class is also a Notifier; that is, it can send notification whenever an attribute or reference is changed. This is an important property, allowing EMF objects to be observed, for example, to update views or other dependent objects.

Notification observers (or listeners) in EMF are called adapters because in addition to their observer status, they are often used to extend the behavior (i.e., support additional interfaces without subclassing) of the object they're attached to. An adapter, as a simple observer, can be attached to any EObject (e.g., a PurchaseOrder) by adding to its adapter list like this:

Adapter poObserver = ...

After doing this, the notifyChanged() method will be called, on poObserver, whenever a state change occurs in the purchase order (e.g., if the setBillTo() method is called), as shown in Figure 2.7.

Figure 2.7

Figure 2.7 Calling the notifyChanged() method.

Unlike simple observers, attaching an adapter as a behavior extension is normally done using an adapter factory. An adapter factory is asked to adapt an object with an extension of the required type, something like this:

PurchaseOrder aPurchaseOrder = ...
AdapterFactory somePOAdapterFactory = ...
Object poExtensionType = ...
if (somePOAdapterFactory.isFactoryForType(poExtensionType))
  Adapter poAdapter =
    somePOAdapterFactory.adapt(aPurchaseOrder, poExtensionType);

Often, the poExtensionType represents some interface supported by the adapter. For example, the argument could be the actual java.lang.Class for an interface of the chosen adapter. The returned adapter can then be downcast to the requested interface, like this:

POAdapter poAdapter =

If the adapter of the requested type is already attached to the object, then adapt() will return the existing adapter; otherwise it will create a new one. In EMF, the adapter factory is the one responsible for creating the adapter; the EMF object itself has no notion of being able to adapt itself. This approach allows greater flexibility to implement the same behavioral extension in more than one way, as different factories can return different implementation for a given extension type.

As you can see, an adapter must be attached to each individual EObject that it wants to observe. Sometimes, you might want to be informed of state changes to any object in a containment hierarchy, a resource, or even any of a set of related resources. Rather than requiring you to walk through the hierarchy and attach your observer to each object, EMF provides a very convenient adapter class, EContentAdapter, that can be used for this purpose. It can be attached to a root object, a resource, or even a resource set, and it will automatically attach itself to all the contents. It will then receive notification of state changes to any of the objects and will even respond to content change notifications itself, by attaching or detaching itself as appropriate.

Adapters are used extensively in EMF as observers and to extend behavior. They are the foundation for the UI and command support provided by EMF.Edit, as we will see in Chapter 3. We'll also look at how they work in much more detail in Chapter 16.

2.5.2 Object Persistence

The ability to persist and reference other persisted objects, is one of the most important benefits of EMF modeling; it's the foundation for fine-grained data integration between applications. EMF provides simple, yet powerful, mechanisms for managing object persistence.

As we've seen earlier, Ecore models are serialized using XMI. Actually, EMF includes a default XMI serializer that can be used to persist objects generically from any model, not just Ecore. Even better, if your model is defined using an XML Schema, EMF allows you to persist your objects as an XML instance document conforming to that schema. The persistence framework, combined with the code generated for your model, handles all this for you.

Above and beyond the default serialization support, EMF allows you to save your objects in any persistent form you like. In this case you'll also need to write the actual serialization code yourself, but once you do that the model will transparently be able to reference (and be referenced by) objects in other models and documents, regardless of how they're persisted.

When we looked at the properties of a generated model class in Section 2.4.1, we pointed out that there are two methods related to persistence: eContainer() and eResource(). To understand how they work, let's start with the following example:

PurchaseOrder aPurchaseOrder =
aPurchaseOrder.setBillTo("123 Maple Street");

Item aItem = POFactory.eINSTANCE.createItem();


Here we've created a PurchaseOrder and an Item using the generated classes from our purchase order model. We then added the Item to the items reference by calling getItems().add().

Whenever an object is added to a containment reference, which items is, it also sets the container of the added object. So, in our example, if we were to call aItem.eContainer() now, it would return the purchase order, aPurchaseOrder.12 The purchase order itself is not in any container, so calling eContainer() on it would return null. Note also that calling the eResource() method on either object would also return null at this point.

Now, to persist this pair of objects, we need to put them into a resource. Interface Resource is used to represent a physical storage location (e.g., a file). To persist our objects, all we need to do is add the root object (i.e., the purchase order) to a resource like this:

Resource poResource = ...

After adding the purchase order to the resource, calling eResource() on either object will return poResource. The item (aItem) is in the resource via its container (aPurchaseOrder).

Now that we've put the two objects into the resource, we can save them by simply calling save()on the resource. That seems simple enough, but where did we get the resource from in the first place? To understand how it all fits together we need to look at another important interface in the persistence framework: ResourceSet.

A ResourceSet, as its name implies, is a set of resources that are accessed together to allow for potential cross-document references among them. It's also the factory for its resources. So, to complete our example, we would create the resource, add the purchase order to it, and then save it like this:13

ResourceSet resourceSet = new ResourceSetImpl();
URI fileURI =
  URI.createFileURI(new File("mypo.xml").getAbsolutePath());
Resource poResource = resourceSet.createResource(fileURI);

Class ResourceSetImpl chooses the resource implementation class using an implementation registry. Resource implementations are registered, globally or local to the resource set, based on a URI scheme, file extension, or other possible criteria. If no specific resource implementation applies for the specified URI, then EMF's default XMI resource implementation will be used.

Assuming that we haven't registered a different resource implementation, after saving our simple resource, we'd get an XMI file, mypo.xml, that looks something like this:

<?xml version="1.0" encoding="UTF-8"?>
<po:PurchaseOrder xmi:version="2.0"
    billTo="123 Maple Street">
  <items productName="Apples" quantity="12" price="0.5"/>

Now that we've been able to save our model instance, let's look at how we would load it again. Loading is also done using a resource set like this:

ResourceSet resourceSet = new ResourceSetImpl();
URI fileURI =
  URI.createFileURI(new File("mypo.xml").getAbsolutePath());
Resource poResource = resourceSet.getResource(fileURI, true);
PurchaseOrder aPurchaseOrder =

Notice that because we know that the resource has our single purchase order at its root, we simply get the first element and downcast.

The resource set also manages demand load for cross-document references, if there are any. When loading a resource, any cross-document references that are encountered will use a proxy object instead of the actual target. These proxies will then be resolved lazily when they are first used.

In our simple example, we actually have no cross-document references; the purchase order contains the item, and they are both in the same resource. Imagine, however, that we had modeled items as a non-containment reference as shown in Figure 2.8.

Figure 2.8

Figure 2.8 items as a simple reference.

Notice the missing black diamond on the PurchaseOrder end of the association, indicating a simple reference as opposed to a by-value aggregation (containment reference). If we make this change using Java annotations instead of UML, the getItems() method would need to change to this:

 * @model type="Item"
List getItems();

Now that items is not a containment reference, we'll need to explicitly call getContents().add() on a resource for the item, just like we previously did for the purchase order. We also have the option of adding it to the same resource as the purchase order, or to a different one. If we choose to put the items into separate resources, then demand loading would come into play, as shown in Figure 2.9. In Figure 2.9, Resource 1 (which could contain our purchase order, for example) contains cross-document references to Resource 2 (e.g., containing our item). When we load Resource 1 by calling getResource() for "uri 1", any references to objects in Resource 2 (i.e., "uri 2") will simply be set to proxies. A proxy is an uninitialized instance of the target class, but with the actual object's URI stored in it. Later, when we access the object—for example, by calling aPurchaseOrder.getItems().get(0)—Resource 2 will be demand loaded and the proxy will be resolved (i.e., replaced with the target object).

Figure 2.9

Figure 2.9 Resource set demand loading of resources.

Although, as we saw earlier, objects in containment references are implicitly included in their container's resource by default, it is also possible to enable cross-resource containment. In Chapters 10 and 15, we'll explore this topic, and look at demand loading, proxies, and proxy resolution in greater detail.

2.5.3 The Reflective EObject API

As we observed in Section 2.4.1, every generated model class implements the EMF base interface, EObject. Among other things, EObject defines a generic, reflective API for manipulating instances:

public interface EObject
  Object eGet(EStructuralFeature feature);
  void eSet(EStructuralFeature feature, Object newValue);

  boolean eIsSet(EStructuralFeature feature);
  void eUnset(EStructuralFeature feature);


We can use this reflective API, instead of the generated methods, to read and write the model. For example, we can set the shipTo attribute of the purchase order like this:

aPurchaseOrder.eSet(shipToAttribute, "123 Maple Street");

We can read it back like this:

String shipTo = (String)aPurchaseOrder.eGet(shipToAttribute);

We can also create a purchase order reflectively by calling a generic create method on the factory like this:

EObject aPurchaseOrder =

If you're wondering where the metaobjects, purchaseOrderClass and shipToAttribute, and the poFactory come from, the answer is that you can get them using generated static fields like this:

POFactory poFactory = POFactory.eINSTANCE;
EClass purchaseOrderClass = POPackage.Literals.PURCHASE_ORDER;
EAttribute shipToAttribute =

The EMF code generator also generates efficient implementations of the reflective methods. They are slightly less efficient than the generated getShipTo() and setShipTo() methods (the reflective methods dispatch to the generated ones through a generated switch statement), but they open up the model for completely generic access. For example, the reflective methods are used by EMF.Edit to implement a full set of generic commands (e.g., AddCommand, RemoveCommand, SetCommand) that can be used on any model. We'll talk more about this in Chapter 3.

Notice that in addition to the eGet() and eSet() methods, the reflective EObject API includes two more methods: eIsSet() and eUnset(). The eIsSet() method can be used to find out if an attribute is set or not, whereas eUnset() can be used to unset or reset it. The generic XMI serializer, for example, uses eIsSet() to determine which attributes need to be serialized during a resource save operation. We'll talk more about the "unset" state, and its significance on certain models, in Chapters 5 and 10.

2.5.4 Dynamic EMF

Until now, we've only ever considered the value of EMF in generating implementations of models. Sometimes, we would like to simply share objects without requiring generated implementation classes to be available. A simple interpretive implementation would be good enough.

A particularly interesting characteristic of the reflective API is that it can also be used to manipulate instances of dynamic, non-generated, classes. Imagine if we hadn't created the purchase order model or run the EMF generator to produce the Java implementation classes in the usual way. Instead, we could simply create the Ecore model at runtime, something like this:

EPackage poPackage = EcoreFactory.eINSTANCE.createEPackage();

EClass purchaseOrderClass = EcoreFactory.eINSTANCE.createEClass();

EClass itemClass = EcoreFactory.eINSTANCE.createEClass();

EAttribute shipToAttribute =

// and so on ...

Here we have an in-memory Ecore model, for which we haven't generated any Java classes. We can now create a purchase order instance and initialize it using the same reflective calls as we used in the previous section:

EFactory poFactory = poPackage.getEFactoryInstance();
EObject aPurchaseOrder = poFactory.create(purchaseOrderClass);
aPurchaseOrder.eSet(shipToAttribute, "123 Maple Street");

Because there is no generated PurchaseOrderImpl class, the factory will create an instance of EObjectImpl instead.14 EObjectImpl provides a default dynamic implementation of the reflective API. As you'd expect, this implementation is slower than the generated one, but the behavior is exactly the same.

An even more interesting scenario involves a mixture of generated and dynamic classes. For example, assume that we had generated class PurchaseOrder in the usual way and now we'd like to create a dynamic subclass of it.

EClass subPOClass = EcoreFactory.eINSTANCE.createEClass();

If we now instantiate an instance of our dynamic class SubPO, then the factory will detect the generated base class and will instantiate it instead of EObjectImpl. The significance of this is that any accesses we make to attributes or references that come from the base class will call the efficient generated implementations in class PurchaseOrderImpl:

String shipTo = aSubPO.eGet(shipToAttribute);

Only features that come from the derived (dynamic) class will use the slower dynamic implementation. Another direct benefit of this approach is that any SubPO object is actually an instance of the Java interface PurchaseOrder, as reported by the instanceof operator.

The most important point of all of this is that, when using the reflective API, the presence (or lack thereof) of generated implementation classes is completely transparent. All you need is the Ecore model in memory. If generated implementation classes are (later) added to the class path, they will then be used. From the client's perspective, the only thing that will change is the speed of the code.

2.5.5 Foundation for Data Integration

The last few sections have shown various features of the runtime framework that support sharing of data. Section 2.5.1 described how change notification is an intrinsic property of every EMF object, and how adapters can be used to support open-ended extension. In Section 2.5.2, we showed how the EMF persistence framework uses Resources and ResourceSets to support cross-document referencing, demand loading of documents, and arbitrary persistent forms. Finally, in Sections 2.5.3 and 2.5.4 we saw how EMF supports generic access to EMF models, including ones that might be partially or completely dynamic (i.e., without generated implementation classes).

In addition to these features, the runtime framework provides a number of convenience classes and utility functions to help manage the sharing of objects. For example, a utility class for finding object cross-references (EcoreUtil. CrossReferencer and its subclasses) can be used to find any uses of an object (e.g., to clean up references when deleting the object) and any unresolved proxies in a resource, among other things.

All these features, combined with an intrinsic property of models—that they are higher level descriptions that can more easily be shared—provide all the needed ingredients to foster fine-grained data integration. While Eclipse itself provides a wonderful platform for integration at the UI and file level, EMF builds on this capability to enable applications to integrate at a much finer granularity than would otherwise be possible. We've seen how EMF can be used to share data reflectively, even without using the EMF code generation support. Whether dynamic or generated, EMF models are the foundation for fine-grained data integration in Eclipse.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information

To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.


Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.


If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information

Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.


This site is not directed to children under the age of 13.


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information

If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information

Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents

California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure

Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact

Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice

We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020