📄 arrayconverter.java
字号:
if (onlyFirstToString) {
size = 1;
}
// Create a StringBuffer containing a delimited list of the values
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < size; i++) {
if (i > 0) {
buffer.append(delimiter);
}
Object element = iterator == null ? Array.get(value, i) : iterator.next();
element = elementConverter.convert(String.class, element);
if (element != null) {
buffer.append(element);
}
}
return buffer.toString();
}
/**
* Handles conversion to an array of the specified type.
*
* @param type The type to which this value should be converted.
* @param value The input value to be converted.
* @return The converted value.
* @throws Throwable if an error occurs converting to the specified type
*/
protected Object convertToType(Class type, Object value) throws Throwable {
if (!type.isArray()) {
throw new ConversionException(toString(getClass())
+ " cannot handle conversion to '"
+ toString(type) + "' (not an array).");
}
// Handle the source
int size = 0;
Iterator iterator = null;
if (value.getClass().isArray()) {
size = Array.getLength(value);
} else {
Collection collection = convertToCollection(type, value);
size = collection.size();
iterator = collection.iterator();
}
// Allocate a new Array
Class componentType = type.getComponentType();
Object newArray = Array.newInstance(componentType, size);
// Convert and set each element in the new Array
for (int i = 0; i < size; i++) {
Object element = iterator == null ? Array.get(value, i) : iterator.next();
// TODO - probably should catch conversion errors and throw
// new exception providing better info back to the user
element = elementConverter.convert(componentType, element);
Array.set(newArray, i, element);
}
return newArray;
}
/**
* Returns the value unchanged.
*
* @param value The value to convert
* @return The value unchanged
*/
protected Object convertArray(Object value) {
return value;
}
/**
* Converts non-array values to a Collection prior
* to being converted either to an array or a String.
* </p>
* <ul>
* <li>{@link Collection} values are returned unchanged</li>
* <li>{@link Number}, {@link Boolean} and {@link java.util.Date}
* values returned as a the only element in a List.</li>
* <li>All other types are converted to a String and parsed
* as a delimited list.</li>
* </ul>
*
* <strong>N.B.</strong> The method is called by both the
* {@link ArrayConverter#convertToType(Class, Object)} and
* {@link ArrayConverter#convertToString(Object)} methods for
* <i>non-array</i> types.
*
* @param type The type to convert the value to
* @param value value to be converted
* @return Collection elements.
*/
protected Collection convertToCollection(Class type, Object value) {
if (value instanceof Collection) {
return (Collection)value;
}
if (value instanceof Number ||
value instanceof Boolean ||
value instanceof java.util.Date) {
List list = new ArrayList(1);
list.add(value);
return list;
}
return parseElements(type, value.toString());
}
/**
* Return the default value for conversions to the specified
* type.
* @param type Data type to which this value should be converted.
* @return The default value for the specified type.
*/
protected Object getDefault(Class type) {
if (type.equals(String.class)) {
return null;
}
Object defaultValue = super.getDefault(type);
if (defaultValue == null) {
return null;
}
if (defaultValue.getClass().equals(type)) {
return defaultValue;
} else {
return Array.newInstance(type.getComponentType(), defaultSize);
}
}
/**
* Provide a String representation of this array converter.
*
* @return A String representation of this array converter
*/
public String toString() {
StringBuffer buffer = new StringBuffer();
buffer.append(toString(getClass()));
buffer.append("[UseDefault=");
buffer.append(isUseDefault());
buffer.append(", ");
buffer.append(elementConverter.toString());
buffer.append(']');
return buffer.toString();
}
/**
* <p>Parse an incoming String of the form similar to an array initializer
* in the Java language into a <code>List</code> individual Strings
* for each element, according to the following rules.</p>
* <ul>
* <li>The string is expected to be a comma-separated list of values.</li>
* <li>The string may optionally have matching '{' and '}' delimiters
* around the list.</li>
* <li>Whitespace before and after each element is stripped.</li>
* <li>Elements in the list may be delimited by single or double quotes.
* Within a quoted elements, the normal Java escape sequences are valid.</li>
* </ul>
*
* @param type The type to convert the value to
* @param value String value to be parsed
* @return List of parsed elements.
*
* @throws ConversionException if the syntax of <code>svalue</code>
* is not syntactically valid
* @throws NullPointerException if <code>svalue</code>
* is <code>null</code>
*/
private List parseElements(Class type, String value) {
if (log().isDebugEnabled()) {
log().debug("Parsing elements, delimiter=[" + delimiter + "], value=[" + value + "]");
}
// Trim any matching '{' and '}' delimiters
value = value.trim();
if (value.startsWith("{") && value.endsWith("}")) {
value = value.substring(1, value.length() - 1);
}
try {
// Set up a StreamTokenizer on the characters in this String
StreamTokenizer st = new StreamTokenizer(new StringReader(value));
st.whitespaceChars(delimiter , delimiter); // Set the delimiters
st.ordinaryChars('0', '9'); // Needed to turn off numeric flag
st.wordChars('0', '9'); // Needed to make part of tokens
for (int i = 0; i < allowedChars.length; i++) {
st.ordinaryChars(allowedChars[i], allowedChars[i]);
st.wordChars(allowedChars[i], allowedChars[i]);
}
// Split comma-delimited tokens into a List
List list = null;
while (true) {
int ttype = st.nextToken();
if ((ttype == StreamTokenizer.TT_WORD) || (ttype > 0)) {
if (list == null) {
list = new ArrayList();
}
list.add(st.sval.trim());
} else if (ttype == StreamTokenizer.TT_EOF) {
break;
} else {
throw new ConversionException("Encountered token of type "
+ ttype + " parsing elements to '" + toString(type) + ".");
}
}
if (list == null) {
list = Collections.EMPTY_LIST;
}
if (log().isDebugEnabled()) {
log().debug(list.size() + " elements parsed");
}
// Return the completed list
return (list);
} catch (IOException e) {
throw new ConversionException("Error converting from String to '"
+ toString(type) + "': " + e.getMessage(), e);
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -