Java tutorial
/** * Copyright (c) 2009-2011 Zauber S.A. <http://www.zaubersoftware.com/> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ar.com.zauber.commons.mom; import java.util.Iterator; import org.apache.commons.beanutils.BeanMap; /** * A delayed map that projects an object into a map. The logic is the following: * Null attributes are converted into null, mappeable arrays object attributes * are converted into collections of maps, mappeable object attributes are * converted into maps, and any other attribute is left unchanged. */ public class AttributesMap extends BeanMap { private final MapObjectMapper mom; public AttributesMap(final Object object, final MapObjectMapper mom) { super(object); this.mom = mom; } @Override public final Object get(final Object name) { Object value = super.get(name); if (value == null) { return null; } return transformValue(value, value.getClass()); } private Object transformValue(final Object value, final Class<?> valueClazz) { if (mom.isMappeableArray(valueClazz)) { return mom.toMap((Object[]) value); } if (mom.isMappeable(valueClazz)) { return mom.toMap(value); } return value; } @Override @SuppressWarnings("unchecked") public final String toString() { /* * This is rough copy paste of the original toString implementation of * AbstractMap, that BeanMap overrides */ Iterator<java.util.Map.Entry<String, Object>> i = entrySet().iterator(); if (!i.hasNext()) { return "{}"; } StringBuilder sb = new StringBuilder(); sb.append('{'); for (;;) { java.util.Map.Entry<String, Object> e = i.next(); String key = e.getKey(); Object value = e.getValue(); sb.append(key); sb.append('='); sb.append(value == this ? "(this Map)" : value); if (!i.hasNext()) { return sb.append('}').toString(); } sb.append(", "); } } }