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