📄 arrayconverter.java
字号:
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.beanutils.converters;
import java.util.Collections;
import java.util.List;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Collection;
import java.io.StreamTokenizer;
import java.io.StringReader;
import java.io.IOException;
import java.lang.reflect.Array;
import org.apache.commons.beanutils.ConversionException;
import org.apache.commons.beanutils.Converter;
/**
* Generic {@link Converter} implementaion that handles conversion
* to and from <b>array</b> objects.
* <p>
* Can be configured to either return a <i>default value</i> or throw a
* <code>ConversionException</code> if a conversion error occurs.
* <p>
* The main features of this implementation are:
* <ul>
* <li><b>Element Conversion</b> - delegates to a {@link Converter},
* appropriate for the type, to convert individual elements
* of the array. This leverages the power of existing converters
* without having to replicate their functionality for converting
* to the element type and removes the need to create a specifc
* array type converters.</li>
* <li><b>Arrays or Collections</b> - can convert from either arrays or
* Collections to an array, limited only by the capability
* of the delegate {@link Converter}.</li>
* <li><b>Delimited Lists</b> - can Convert <b>to</b> and <b>from</b> a
* delimited list in String format.</li>
* <li><b>Conversion to String</b> - converts an array to a
* <code>String</code> in one of two ways: as a <i>delimited list</i>
* or by converting the first element in the array to a String - this
* is controlled by the {@link ArrayConverter#setOnlyFirstToString(boolean)}
* parameter.</li>
* <li><b>Multi Dimensional Arrays</b> - its possible to convert a <code>String</code>
* to a multi-dimensional arrays, by embedding {@link ArrayConverter}
* within each other - see example below.</li>
* <li><b>Default Value</b></li>
* <ul>
* <li><b><i>No Default</b></i> - use the
* {@link ArrayConverter#ArrayConverter(Class, Converter)}
* constructor to create a converter which throws a
* {@link ConversionException} if the value is missing or
* invalid.</li>
* <li><b><i>Default values</b></i> - use the
* {@link ArrayConverter#ArrayConverter(Class, Converter, int)}
* constructor to create a converter which returns a <i>default
* value</i>. The <i>defaultSize</i> parameter controls the
* <i>default value</i> in the following way:</li>
* <ul>
* <li><i>defaultSize < 0</i> - default is <code>null</code></li>
* <li><i>defaultSize = 0</i> - default is an array of length zero</li>
* <li><i>defaultSize > 0</i> - default is an array with a
* length specified by <code>defaultSize</code> (N.B. elements
* in the array will be <code>null</code>)</li>
* </ul>
* </ul>
* </ul>
*
* <h3>Parsing Delimited Lists</h3>
* This implementation can convert a delimited list in <code>String</code> format
* into an array of the appropriate type. By default, it uses a comma as the delimiter
* but the following methods can be used to configure parsing:
* <ul>
* <li><code>setDelimiter(char)</code> - allows the character used as
* the delimiter to be configured [default is a comma].</li>
* <li><code>setAllowedChars(char[])</code> - adds additional characters
* (to the default alphabetic/numeric) to those considered to be
* valid token characters.
* </ul>
*
* <h3>Multi Dimensional Arrays</h3>
* It is possible to convert a <code>String</code> to mulit-dimensional arrays by using
* {@link ArrayConverter} as the element {@link Converter}
* within another {@link ArrayConverter}.
* <p>
* For example, the following code demonstrates how to construct a {@link Converter}
* to convert a delimited <code>String</code> into a two dimensional integer array:
* <p>
* <pre>
* // Construct an Integer Converter
* IntegerConverter integerConverter = new IntegerConverter();
*
* // Construct an array Converter for an integer array (i.e. int[]) using
* // an IntegerConverter as the element converter.
* // N.B. Uses the default comma (i.e. ",") as the delimiter between individual numbers
* ArrayConverter arrayConverter = new ArrayConverter(int[].class, integerConverter);
*
* // Construct a "Matrix" Converter which converts arrays of integer arrays using
* // the pre-ceeding ArrayConverter as the element Converter.
* // N.B. Uses a semi-colon (i.e. ";") as the delimiter to separate the different sets of numbers.
* // Also the delimiter used by the first ArrayConverter needs to be added to the
* // "allowed characters" for this one.
* ArrayConverter matrixConverter = new ArrayConverter(int[][].class, arrayConverter);
* matrixConverter.setDelimiter(';');
* matrixConverter.setAllowedChars(new char[] {','});
*
* // Do the Conversion
* String matrixString = "11,12,13 ; 21,22,23 ; 31,32,33 ; 41,42,43";
* int[][] result = (int[][])matrixConverter.convert(int[][].class, matrixString);
* </pre>
*
* @version $Revision: 555824 $ $Date: 2007-07-13 01:27:15 +0100 (Fri, 13 Jul 2007) $
* @since 1.8.0
*/
public class ArrayConverter extends AbstractConverter {
private Converter elementConverter;
private int defaultSize;
private char delimiter = ',';
private char[] allowedChars = new char[] {'.', '-'};
private boolean onlyFirstToString = true;
// ----------------------------------------------------------- Constructors
/**
* Construct an <b>array</b> <code>Converter</code> with the specified
* <b>component</b> <code>Converter</code> that throws a
* <code>ConversionException</code> if an error occurs.
*
* @param defaultType The default array type this
* <code>Converter</code> handles
* @param elementConverter Converter used to convert
* individual array elements.
*/
public ArrayConverter(Class defaultType, Converter elementConverter) {
super(defaultType);
if (!defaultType.isArray()) {
throw new IllegalArgumentException("Default type must be an array.");
}
if (elementConverter == null) {
throw new IllegalArgumentException("Component Converter is missing.");
}
this.elementConverter = elementConverter;
}
/**
* Construct an <b>array</b> <code>Converter</code> with the specified
* <b>component</b> <code>Converter</code> that returns a default
* array of the specified size (or <code>null</code>) if an error occurs.
*
* @param defaultType The default array type this
* <code>Converter</code> handles
* @param elementConverter Converter used to convert
* individual array elements.
* @param defaultSize Specifies the size of the default array value or if less
* than zero indicates that a <code>null</code> default value should be used.
*/
public ArrayConverter(Class defaultType, Converter elementConverter, int defaultSize) {
this(defaultType, elementConverter);
this.defaultSize = defaultSize;
Object defaultValue = null;
if (defaultSize >= 0) {
defaultValue = Array.newInstance(defaultType.getComponentType(), defaultSize);
}
setDefaultValue(defaultValue);
}
/**
* Set the delimiter to be used for parsing a delimited String.
*
* @param delimiter The delimiter [default ',']
*/
public void setDelimiter(char delimiter) {
this.delimiter = delimiter;
}
/**
* Set the allowed characters to be used for parsing a delimited String.
*
* @param allowedChars Characters which are to be considered as part of
* the tokens when parsing a delimited String [default is '.' and '-']
*/
public void setAllowedChars(char[] allowedChars) {
this.allowedChars = allowedChars;
}
/**
* Indicates whether converting to a String should create
* a delimited list or just convert the first value.
*
* @param onlyFirstToString <code>true</code> converts only
* the first value in the array to a String, <code>false</code>
* converts all values in the array into a delimited list (default
* is <code>true</code>
*/
public void setOnlyFirstToString(boolean onlyFirstToString) {
this.onlyFirstToString = onlyFirstToString;
}
/**
* Handles conversion to a String.
*
* @param value The value to be converted.
* @return the converted String value.
* @throws Throwable if an error occurs converting to a String
*/
protected String convertToString(Object value) throws Throwable {
int size = 0;
Iterator iterator = null;
Class type = value.getClass();
if (type.isArray()) {
size = Array.getLength(value);
} else {
Collection collection = convertToCollection(type, value);
size = collection.size();
iterator = collection.iterator();
}
if (size == 0) {
return (String)getDefault(String.class);
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -