Jeffrey Ricker is an experienced technology development executive with 15 years of leadership in defense and the private sector. He is the principal of Jeffrey Ricker LLC, providing expertise in Eclipse, RCP and OSGi to Fortune 500 and start-up clients. Previously, he was the founder of Distributed Instruments and XML Solutions Corp. Jeffrey has posted 5 posts at DZone. You can read more from them at their website. View Full User Profile

Eclipse Adapters - A Hands-On, Hand-Holding Explanation

  • submit to reddit

When programming Eclipse plug-ins, you quickly come face to face with Eclipse adapters. If you are not familiar with the adapter pattern, adapters can be confusing. Eclipse adapters are actually very simple, and I hope to make them even simpler with this article.

Adapters work on a simple premise: Given some adaptable object A, get me the relevant object of type B for it. The Eclipse adapter interface is shown in Listing 1. The interface returns an object which is an instance of the given class associated with the object or it returns null if no such associated object can be found.

package org.eclipse.core.runtime;
public interface IAdaptable {
public Object getAdapter(Class adapter);

Listing 1: The Eclipse Adapter Interface 

For instance, if I wanted to go from apples to oranges then I would do something like Listing 2. In this example, IApple extends the IAdaptable interface.

IApple macintosh = new Macintosh();
IOrange orange = (IOrange) macintosh.getAdapter(IOrange.class);
if (orange==null)
log("No orange");
log("Created a "+ orange.getClass().getCanonicalName()); 

Listing 2: Adapting from Apples to Oranges 

One of the primary uses of adapters is to separate model code from view code, as in a view-model-controller or view model-presenter pattern. We would not want to put presentation information like icons in our apple model. We would another class to handle how to present it. We could do this with adapters as shown in Listing 3.

IApple apple = new Macintosh();
ILableProvider label = (ILabelProvider)apple.getAdapter(ILabelProvider.class);
String text = label.getText(apple);

Listing 3: Using Adapters to seperate model from view. 

Adapters allow us to transform objects into other purposes that the objects did not need to anticipate. For instance, the apple objects in the Listing 3 do not need to know anything about the label provider. We can implement the getAdapter() method manually for each apple object, but that would defeat the purpose. Instead, we should defer the adaptation to the platform as shown in Listing 4.

public abstract class Fruit implements IAdaptable{
public Object getAdapter(Class adapter){
return Platform.getAdapterManager().getAdapter(this, adapter);

Listing 4: Adapting through the platform

Published at DZone with permission of its author, Jeffrey Ricker.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)