Jump to: navigation, search

E4/EAS/Adapting Objects

< E4‎ | EAS

The adapter pattern is widely used in the Eclipse platform as a way for different classes to retrieve information about a given object. This can usually be seen by how different views react completely different to a given object. Consider how the 'Javadoc' view renders the javadoc specification of a given class but the 'Outline' view provides an overview of the entire class instead of just the item under the current text caret.

Eclipse 3.x API

Getting an IAdapterManager

The existing IAdapterManager can currently either be retrieved directly via a static method (Platform.getAdapterManger()) or queried through via OSGi as a service.

Adapting objects

In Eclipse 3.x, there is the org.eclipse.core.runtime.IAdaptable interface that types can implement/extend if they wish clients to adapt their object to another object.

Implementation

public interface IModelProvider {
 
  public Model getModel();
 
}
 
public class ModelEditor implements IAdaptable, IModelProvider {
 
  private Model model;
 
  public Model getModel() {
    return model;
  }
 
  public Object getAdapter(Class adapter) {
    if (adapter == IModelProvider.class) {
      return this;
    }
    return null;
  }
}

Client code

IModelProvider modelProvider = (IModelProvider) editor.getAdapter(IModelProvider.class);
if (modelProvider != null) {
  // do something with it
}

e4 (Java)

Getting an IAdapterManager

The adapter manager can be easily queried for by asking the Eclipse context.

private IAdapterManager getAdapterManager(IEclipseContext context) {
  return (IAdapterManager) context.get(IAdapterManager.class.getName());
}

Adapting objects

If generics could be used, the client code can be simplified as casting would no longer be required.

IAdaptable definition

public interface IAdaptable {
 
  public <T> T getAdapter(Class<T> cls);
 
}

Implementation

public interface IModelProvider {
 
  public Model getModel();
 
}
 
public class ModelEditor implements IAdaptable, IModelProvider {
 
  private Model model;
 
  public Model getModel() {
    return model;
  }
 
  public <T> T getAdapter(Class<T> adapter) {
    if (adapter == IModelProvider.class) {
      return (T) this;
    }
    return null;
  }
}

Client code

// casting no longer required in client code
IModelProvider modelProvider = editor.getAdapter(IModelProvider.class);
if (modelProvider != null) {
  // do something with it
}