package net.sourceforge.javautil.groovy.util;
import groovy.lang.GroovyObject;
import groovy.lang.MetaProperty;
import java.util.HashMap;
/**
* This is an implementation of the object map that will attempt to set/get properties on the GroovyObject
* that was passed before doing normal map store/retreive functionality.
*
* @author elponderador
*/
public class AttributeObjectMap<K> extends HashMap<K, Object> {
private GroovyObject object;
public AttributeObjectMap(GroovyObject object) {
this.object = object;
}
/**
* We see if there is a MetaProperty on the object with this key name, if so, we get its value.
* Otherwise we retrieve any possible value in this map.
*/
@Override public Object get(Object key) {
MetaProperty prop = object.getMetaClass().getMetaProperty(String.valueOf(key));
if (prop != null) return prop.getProperty(object);
return super.get(key);
}
/**
* We see if there is a MetaProperty on the object with this key name, if so, we try to set its value.
* Otherwise we store the value in this map.
*/
@Override public Object put(K key, Object value) {
MetaProperty prop = object.getMetaClass().getMetaProperty(String.valueOf(key));
if (prop != null) {
Object oldValue = prop.getProperty(object);
prop.setProperty(object, value);
return oldValue;
}
return super.put(key, value);
}
@Override public boolean containsKey(Object key) {
return super.containsKey(key) || object.getMetaClass().getMetaProperty(String.valueOf(key)) != null;
}
}