001package org.kohsuke.args4j.spi;
002
003import java.lang.reflect.Field;
004import java.util.ArrayList;
005import java.util.List;
006
007import org.openimaj.util.pair.IndependentPair;
008
009/**
010 * A field getter calls .toString() on the underlying object
011 * 
012 * @author Sina Samangooei (ss@ecs.soton.ac.uk)
013 * @author Jonathon Hare (jsh2@ecs.soton.ac.uk)
014 * 
015 */
016public class FieldGetter extends AbstractGetter<String> {
017
018        /**
019         * @param name
020         * @param bean
021         * @param f
022         */
023        public FieldGetter(String name, Object bean, Field f) {
024                super(name, bean, f);
025        }
026
027        @Override
028        public List<IndependentPair<String, Class<?>>> getStringValues() {
029                List<IndependentPair<String, Class<?>>> ret = new ArrayList<IndependentPair<String, Class<?>>>();
030
031                Object b;
032                try {
033                        b = f.get(bean);
034                } catch (Exception _ignore) {
035                        // try again
036                        f.setAccessible(true);
037                        try {
038                                b = f.get(bean);
039
040                        } catch (Exception e) {
041                                throw new IllegalAccessError(e.getMessage());
042                        }
043                }
044                
045                if (b == null)
046                        return ret;
047                
048                Class<?> c = b.getClass();
049                IndependentPair<String, Class<?>> pair;
050                if (c == Boolean.class) {
051                        if (!(Boolean) b) {
052                                pair = new IndependentPair<String, Class<?>>(null, c);
053                        } else {
054                                pair = new IndependentPair<String, Class<?>>(b.toString(), c);
055                        }
056                } else {
057                        pair = new IndependentPair<String, Class<?>>(b.toString(), c);
058                }
059
060                ret.add(pair);
061
062                return ret;
063        }
064}