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 Open Source

  • Twitter Updates

    • @micho Infovia anyone? 2 hours ago
    • After days in Elixir, I write Ruby like: class Scoped.Thing do def baz do do_something() end end And wonder why it doesn’t parse 7 hours ago
    • RT @islomar: A piece of advice for anyone applying for a job: clearly transmit your MOTIVATIONS, GOALS and WHYS, not just a bunch of topics… 11 hours ago
    • RT @realntl: @wycats We want to say "sorry mgmt, we made a mess and need time to rewrite" but "the lang/framework sucks and we need to migr… 20 hours ago
    • @MarkVillacampa Al menos con todo esto, alguna gente aprenderá a actualizarse y por qué. Sobre todo la oposición! 21 hours ago
  • Enter your email address to follow this blog and receive notifications of new posts by email.

    Join 9 other followers

  • Flickr Photos

%d bloggers like this: