Adapting with generics

Wayne Beaton has made some great articles about using adapters in Eclipse to reduce coupling.

In Adapting, the last post of the series, he shows some code to check if an object is or adapts to a given interface. This code has the problem that it needs to be repeated for every interface you need to check against.

The process is:

  1. Check if the object already implements the interface.
  2. If it doesn’t, check if it implements IAdaptable and can adapt to the interface.
  3. If it doesn’t, check if an adapter can be found through the Platform.getAdapterManager().loadAdapter(…)

My solution to avoid repeating code and leverage Java5 generics is this:

private <T> T adaptAs( Class<T> clazz, Object object )
    if ( object == null )
        return null;
    if ( clazz.isAssignableFrom( object.getClass() ) )
        return (T) object;
    if ( object instanceof IAdaptable )
        return (T) ( (IAdaptable) object ).getAdapter( clazz );
        return (T) Platform.getAdapterManager().getAdapter( object, clazz );

More solutions, all of them Java 1.4 compatible, are listed in the eclipse bug 118560.


  • My profile

    View Abel Muño's profile on LinkedIn

    amuino on Twitter

  • My projects

    The cloud market:
    Find the virtual image you need on the cloud.
  • Top Posts

  • Archives

  • Categories

%d bloggers like this: