Print
Creating Adapter Using Dimple

It is a normal design that a module accepts as a parameter a java.util.Map instance and just uses the "Map.get()" method to get certain values. For example:

void someApi(Map map){
  ...
  map.get("somekey");
  ...
}

It would then be quite easy to call someApi if we've got a Map instance (such as HashMap, Properties etc).

It becomes a problem is when we do not have a Map instance. We may sometimes only have an object of proprietary type with similar Map semantics, for example:

interface PropertyMap {
  String getProperty(String name);
  String[] getPropertyNames();
  boolean containsName(String name);
}

In order to call someApi using an instance of PropertyMap, we will need an adapter.

What's annoying is that the java.util.Map interface is quite fat. Implementing all of the declared methods is a pain. Dimple can help here.

The first step is to create an adapter class:

pubilc class PropertyMapAdapter {
  private final PropertyMap pmap;
  public PropertyMapAdapter(PropertyMap pmap) {
    this.pmap = pmap;
  }
  public Object get(Object key) {
    if(key instanceof String) {
      return pmap.getProperty((String)key);
    }
    else return null;
  }
  public Object containsKey(Object key) {
    if(key instanceof String) {
      return pmap.containsName((String)key);
    }
    else return false;
  }
  public Set keySet() {
    HashSet set = new HashSet();
    set.addAll(Arrays.asList(pmap.getPropertyNames()));
    return set;
  }
  public boolean isEmpty() {
    return pmap.getPropertyNames().length==0;
  }
  public int size() {
    return pmap.getPropertyNames().length;
  }
}

There's no need to implement the irrelevant methods. One tip to avoid typo is to make PropertyMapAdapter "implements Map" first, you can then use the IDE to generate the method stubs that you want to implement.

Remove the "implements Map" after you are done to make the class instantiable.

There's just one step left to create the Map instance we need by using dimple:

PropertyMap pmap = ...;
Map map = Implementor.proxy(Map.class, new PropertyMapAdapter(pmap));
someApi(map);

Created by benyu

On Thu Dec 21 10:26:15 CST 2006

Using TimTam

Powered by Atlassian Confluence