001package org.kohsuke.args4j.spi;
002
003import java.lang.reflect.Field;
004import java.util.ArrayList;
005import java.util.List;
006import java.util.Map;
007import java.util.Map.Entry;
008
009import org.kohsuke.args4j.IllegalAnnotationError;
010import org.openimaj.util.pair.IndependentPair;
011
012/**
013 * A getter for map objects
014 * @author Jonathon Hare (jsh2@ecs.soton.ac.uk), Sina Samangooei (ss@ecs.soton.ac.uk)
015 *
016 */
017public class MapGetter extends AbstractGetter<Object>{
018
019        /**
020         * @param name
021         * @param bean
022         * @param f
023         */
024        public MapGetter(String name, Object bean, Field f) {
025                super(name, bean,f);
026        }
027
028        @Override
029        public List<IndependentPair<String, Class<?>>> getStringValues()  {
030                try {
031                        return getListStrings();
032                } catch (Exception _ignore) {
033                        // try again
034            f.setAccessible(true);
035            try {
036                return getListStrings();
037            } catch (Exception e) {
038                throw new IllegalAccessError(e.getMessage());
039            }
040                }
041        }
042
043        private List<IndependentPair<String, Class<?>>> getListStrings() throws IllegalArgumentException, IllegalAccessException {
044                Object o = f.get(bean);
045        if(o==null) {
046            return new ArrayList<IndependentPair<String, Class<?>>>();
047        }
048        if(!(o instanceof Map))
049            throw new IllegalAnnotationError(Messages.ILLEGAL_FIELD_SIGNATURE.format(f));
050        ArrayList<IndependentPair<String, Class<?>>> ret = new ArrayList<IndependentPair<String, Class<?>>>();
051        for(Entry<?, ?> obj : ((Map<?,?>) o).entrySet()){
052                Class<?> objClass = Object.class;
053                IndependentPair<String, Class<?>> pair = new IndependentPair<String, Class<?>>(obj.getKey().toString() + "=" + obj.getValue().toString(),objClass);
054                ret.add(pair);
055        }
056        return ret;
057        }
058        
059        @Override
060        public boolean isMultiValued() {
061                return true;
062        }
063}