001 /*
002 * Copyright 2003-2004 The Apache Software Foundation
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016 package org.apache.commons.convert1.array;
017
018 import java.lang.reflect.Array;
019 import java.util.List;
020 import java.util.Iterator;
021
022 import org.apache.commons.convert1.ConversionException;
023 import org.apache.commons.convert1.Converter;
024
025 import org.apache.commons.convert1.ConvertRegistry;
026
027
028 /**
029 * <p>Standard {@link Converter} implementation that converts an incoming
030 * comma delimited String into a known Java class via another Converter.
031 *
032 * @author Henri Yandell
033 * @version $Id: ArrayConverter.java 155441 2005-02-26 13:19:22Z dirkv $
034 * @since 0.1
035 */
036 public class ArrayConverter implements Converter {
037
038 private ConvertRegistry registry;
039 private Converter converter;
040
041 /**
042 * Handles multiple types of sub-type by reusing a
043 * particular registry for the sub-elements.
044 */
045 public ArrayConverter(ConvertRegistry registry) {
046 this.registry = registry;
047 }
048
049 /**
050 * Handles only one type of element converter.
051 */
052 public ArrayConverter(Converter converter) {
053 this.converter = converter;
054 }
055
056 /**
057 * Convert the specified input object into an output object of the
058 * specified type.
059 *
060 * @param type Data type to which this value should be converted
061 * @param value The input value to be converted
062 *
063 * @exception ConversionException if conversion cannot be performed
064 * successfully
065 */
066 public Object convert(Class toClass, Object value) {
067
068 if (value == null) {
069 return null; // ignore defaults for the moment
070 }
071
072 // parse the comma delimitation.
073 //H? can we abstract this somehow?
074 // An ElementProvider?
075 List elements = StringArrayParser.parseElements(value.toString());
076
077 // assume that toClass is an array??
078 if( toClass.isArray() ) {
079 toClass = toClass.getComponentType();
080 }
081 Object array = Array.newInstance( toClass, elements.size() );
082
083 if(registry != null) {
084 converter = this.registry.lookup( String.class, toClass );
085 }
086
087 Iterator itr = elements.iterator();
088 int idx = 0;
089 while(itr.hasNext()) {
090 Array.set( array, idx, converter.convert( toClass, itr.next() ) );
091 idx++;
092 }
093
094 return array;
095 }
096
097 }