Map Object.

Have you wished you could attach arbitrary data to plain any Java object during the runtime? I have and not once or twice.

Something like adding these two methods “get(Object key)” and “put(Object key, Object data)”.

This often happens when objects, while interacting, need to associate arbitrary data with each other without having the appropriate get/set methods for that data.

During my past experience I have encountered quite a number of scenarios (some of which are described below) requiring that capability with the only solution of having custom sub type of object with addition of those two methods.

  • Caching. In high volume transaction environment where thousands of short lived event objects go thought the system components it might be best to have the components associate the data they retrieve for that event to the event itself instead of caching internally with the reference to that event and later going through the trouble of identifying dead events for cleanup.
  • Identification. Again instead of storing reference to the object internally for later identification the component can associate ID data to the object itself, something like passport in real life..

This has been partially influenced by Servlet API session/request objects with the similar functionalities (which are the most heavily relied upon methods in any Servlet based application written on the earth).
Like in case of Servlet session object it can also be misused.

Sample Code.

// Our object replacement.

public class MapObject extends Object{
 private Map dataMap = null;

 // Map methods
 // The lazy loading can fine tuned further (ie creating HashMap only after 2-4 call to putData)
 // Depending on the environment need to be synchronized. If dealing with POJOs behind EJB facade
 // no need to synchronize.

 public Object getData(Object key){
  if (dataMap == null) return null;
  return dataMap.get(key);

 punlic void putData(Object key, Object data){
  if (dataMap == null) dataMap = new HashMap();
  dataMap.put(key, data);

// Application specific code

public class Event extends MapObject{
 private int id = -1;

 public int getId(){
  return id;

 public void setId(){ = id;

 //other event methods

public interface EventOwnerManager{

 public Owner getOwner(Event event);


public class EventOwnerManagerImpl{
 private static final String OWNER_KEY = EventOwnerManagerImpl.class + "owner";

 // similarly synchronization should be handled as needed

 public Owner getOwner(Event event){
  Owner owner = event.getData(OWNER_KEY);
  if (owner == null) event.putData( OWNER_KEY, owner = longGetOwner(event) );
  return owner;

Leave a Reply

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>