gekefe
gekefe

Reputation: 21

Add an ad-hoc primitive tag/annotation to an EObject instance

Consider an EMF EObject instance:

EObject eObject = ...

Note that I cannot assume more about eObject.

I want to add a boolean readyToBeProcessed tag/annotation/property to this and nothing but this eObject. This means that none of the other objects managed by the EMF framework which are of the same .eClass() should be affected in any way.

Is this possible at all?

The examples I've seen so far either:

  1. created a new EAnnotation and registered the annotation with the eObject's eClass()
  2. created a new EAttribute and registered the annotation with the eObject's eClass()

These approaches, however, modify the eClass() which in my case is unacceptable.

Upvotes: 0

Views: 40

Answers (2)

Banoffee
Banoffee

Reputation: 862

I think your best bet is to manage it on the side.

So for a model-based approach I would create another kind of model serialized alongside your existing one. If you only need simple properties such as booleans and strings, I would simply create a properties file alongside the model resource.

Upvotes: 0

Dimitris
Dimitris

Reputation: 186

One option would be to (ab)use adapters, as follows.

import java.util.HashMap;

import org.eclipse.emf.common.notify.Adapter;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.notify.Notifier;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EcoreFactory;

public class Example {

    public static void main(String[] args) throws Exception {

        // Define an EObject variable and assign it to a random EObject
        EObject eObject = EcoreFactory.eINSTANCE.createEOperation();
        
        ExtraPropertiesAdapter adapter = new ExtraPropertiesAdapter();

        eObject.eAdapters().add(adapter);
        
        // Set the extra readyToBeProcessed "attribute"
        adapter.getProperties().put("readyToBeProcessed", true);
        
        // Get and print the extra readyToBeProcessed attribute
        System.out.println(((ExtraPropertiesAdapter) eObject.eAdapters().
            stream().filter(a -> a instanceof ExtraPropertiesAdapter).findAny().
            orElse(new ExtraPropertiesAdapter())).getProperties().
            get("readyToBeProcessed"));

    }

    public static class ExtraPropertiesAdapter implements Adapter {

        protected HashMap<String, Object> properties = new HashMap<>();

        public HashMap<String, Object> getProperties() {
            return properties;
        }

        @Override
        public void notifyChanged(Notification notification) {}

        @Override
        public Notifier getTarget() { return null; }

        @Override
        public void setTarget(Notifier newTarget) {}

        @Override
        public boolean isAdapterForType(Object type) { return false; }

    }
}

Upvotes: 1

Related Questions