001    package org.picocontainer.converters;
002    
003    import org.picocontainer.Converters;
004    
005    import java.io.File;
006    import java.io.Serializable;
007    import java.lang.reflect.Type;
008    import java.net.URL;
009    import java.util.HashMap;
010    import java.util.Map;
011    
012    /**
013     * Provides some built-in converters used by {@link DefaultPicoContainer}. It
014     * supports by default primitive types (and boxed equivalents) and for
015     * {@link File} and {@link URL} types. Built-in converters can be changed by
016     * extending the class and overriding the method {@link #addBuiltInConverters()}.
017     */
018    @SuppressWarnings("serial")
019    public class BuiltInConverters implements Converters, Serializable {
020    
021        private final Map<Class<?>, Converter<?>> converters = new HashMap<Class<?>, Converter<?>>();
022    
023        public BuiltInConverters() {
024            addBuiltInConverters();
025        }
026    
027        protected void addBuiltInConverters() {
028            addMultiTypeConverter(new IntegerConverter(), Integer.class, Integer.TYPE);
029            addMultiTypeConverter(new DoubleConverter(), Double.class, Double.TYPE);
030            addMultiTypeConverter(new BooleanConverter(), Boolean.class, Boolean.TYPE);
031            addMultiTypeConverter(new LongConverter(), Long.class, Long.TYPE);
032            addMultiTypeConverter(new FloatConverter(), Float.class, Float.TYPE);
033            addMultiTypeConverter(new CharacterConverter(), Character.class, Character.TYPE);
034            addMultiTypeConverter(new ByteConverter(), Byte.class, Byte.TYPE);
035            addMultiTypeConverter(new ShortConverter(), Short.class, Short.TYPE);
036            addConverter(new FileConverter(), File.class);
037            addConverter(new UrlConverter(), URL.class);
038        }
039    
040        private void addMultiTypeConverter(Converter<?> converter, Class<?>... types) {
041            for (Class<?> type : types) {
042                addConverter(converter, type);
043            }
044        }
045    
046        protected void addConverter(Converter<?> converter, Class<?> key) {
047            converters.put(key, converter);
048        }
049    
050        public boolean canConvert(Type type) {
051            return converters.containsKey(type);
052        }
053    
054        public Object convert(String paramValue, Type type) {
055            Converter<?> converter = converters.get(type);
056            if (converter == null) {
057                return null;
058            }
059            return converter.convert(paramValue);
060        }
061    
062    }