001: /*
002: * Copyright 2002-2006 the original author or authors.
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:
017: package org.springframework.util;
018:
019: import java.math.BigDecimal;
020: import java.math.BigInteger;
021: import java.text.NumberFormat;
022: import java.text.ParseException;
023:
024: /**
025: * Miscellaneous utility methods for number conversion and parsing.
026: * Mainly for internal use within the framework; consider Jakarta's
027: * Commons Lang for a more comprehensive suite of string utilities.
028: *
029: * @author Juergen Hoeller
030: * @author Rob Harrop
031: * @since 1.1.2
032: */
033: public abstract class NumberUtils {
034:
035: /**
036: * Convert the given number into an instance of the given target class.
037: * @param number the number to convert
038: * @param targetClass the target class to convert to
039: * @return the converted number
040: * @throws IllegalArgumentException if the target class is not supported
041: * (i.e. not a standard Number subclass as included in the JDK)
042: * @see java.lang.Byte
043: * @see java.lang.Short
044: * @see java.lang.Integer
045: * @see java.lang.Long
046: * @see java.math.BigInteger
047: * @see java.lang.Float
048: * @see java.lang.Double
049: * @see java.math.BigDecimal
050: */
051: public static Number convertNumberToTargetClass(Number number,
052: Class targetClass) throws IllegalArgumentException {
053:
054: Assert.notNull(number, "Number must not be null");
055: Assert.notNull(targetClass, "Target class must not be null");
056:
057: if (targetClass.isInstance(number)) {
058: return number;
059: } else if (targetClass.equals(Byte.class)) {
060: long value = number.longValue();
061: if (value < Byte.MIN_VALUE || value > Byte.MAX_VALUE) {
062: raiseOverflowException(number, targetClass);
063: }
064: return new Byte(number.byteValue());
065: } else if (targetClass.equals(Short.class)) {
066: long value = number.longValue();
067: if (value < Short.MIN_VALUE || value > Short.MAX_VALUE) {
068: raiseOverflowException(number, targetClass);
069: }
070: return new Short(number.shortValue());
071: } else if (targetClass.equals(Integer.class)) {
072: long value = number.longValue();
073: if (value < Integer.MIN_VALUE || value > Integer.MAX_VALUE) {
074: raiseOverflowException(number, targetClass);
075: }
076: return new Integer(number.intValue());
077: } else if (targetClass.equals(Long.class)) {
078: return new Long(number.longValue());
079: } else if (targetClass.equals(Float.class)) {
080: return new Float(number.floatValue());
081: } else if (targetClass.equals(Double.class)) {
082: return new Double(number.doubleValue());
083: } else if (targetClass.equals(BigInteger.class)) {
084: return BigInteger.valueOf(number.longValue());
085: } else if (targetClass.equals(BigDecimal.class)) {
086: // using BigDecimal(String) here, to avoid unpredictability of BigDecimal(double)
087: // (see BigDecimal javadoc for details)
088: return new BigDecimal(number.toString());
089: } else {
090: throw new IllegalArgumentException(
091: "Could not convert number [" + number
092: + "] of type ["
093: + number.getClass().getName()
094: + "] to unknown target class ["
095: + targetClass.getName() + "]");
096: }
097: }
098:
099: /**
100: * Raise an overflow exception for the given number and target class.
101: * @param number the number we tried to convert
102: * @param targetClass the target class we tried to convert to
103: */
104: private static void raiseOverflowException(Number number,
105: Class targetClass) {
106: throw new IllegalArgumentException("Could not convert number ["
107: + number + "] of type [" + number.getClass().getName()
108: + "] to target class [" + targetClass.getName()
109: + "]: overflow");
110: }
111:
112: /**
113: * Parse the given text into a number instance of the given target class,
114: * using the corresponding default <code>decode</code> methods. Trims the
115: * input <code>String</code> before attempting to parse the number. Supports
116: * numbers in hex format (with leading 0x) and in octal format (with leading 0).
117: * @param text the text to convert
118: * @param targetClass the target class to parse into
119: * @return the parsed number
120: * @throws IllegalArgumentException if the target class is not supported
121: * (i.e. not a standard Number subclass as included in the JDK)
122: * @see java.lang.Byte#decode
123: * @see java.lang.Short#decode
124: * @see java.lang.Integer#decode
125: * @see java.lang.Long#decode
126: * @see #decodeBigInteger(String)
127: * @see java.lang.Float#valueOf
128: * @see java.lang.Double#valueOf
129: * @see java.math.BigDecimal#BigDecimal(String)
130: */
131: public static Number parseNumber(String text, Class targetClass) {
132: Assert.notNull(text, "Text must not be null");
133: Assert.notNull(targetClass, "Target class must not be null");
134:
135: String trimmed = text.trim();
136:
137: if (targetClass.equals(Byte.class)) {
138: return Byte.decode(trimmed);
139: } else if (targetClass.equals(Short.class)) {
140: return Short.decode(trimmed);
141: } else if (targetClass.equals(Integer.class)) {
142: return Integer.decode(trimmed);
143: } else if (targetClass.equals(Long.class)) {
144: return Long.decode(trimmed);
145: } else if (targetClass.equals(BigInteger.class)) {
146: return decodeBigInteger(trimmed);
147: } else if (targetClass.equals(Float.class)) {
148: return Float.valueOf(trimmed);
149: } else if (targetClass.equals(Double.class)) {
150: return Double.valueOf(trimmed);
151: } else if (targetClass.equals(BigDecimal.class)
152: || targetClass.equals(Number.class)) {
153: return new BigDecimal(trimmed);
154: } else {
155: throw new IllegalArgumentException(
156: "Cannot convert String [" + text
157: + "] to target class ["
158: + targetClass.getName() + "]");
159: }
160: }
161:
162: /**
163: * Parse the given text into a number instance of the given target class,
164: * using the given NumberFormat. Trims the input <code>String</code>
165: * before attempting to parse the number.
166: * @param text the text to convert
167: * @param targetClass the target class to parse into
168: * @param numberFormat the NumberFormat to use for parsing (if <code>null</code>,
169: * this method falls back to <code>parseNumber(String, Class)</code>)
170: * @return the parsed number
171: * @throws IllegalArgumentException if the target class is not supported
172: * (i.e. not a standard Number subclass as included in the JDK)
173: * @see java.text.NumberFormat#parse
174: * @see #convertNumberToTargetClass
175: * @see #parseNumber(String, Class)
176: */
177: public static Number parseNumber(String text, Class targetClass,
178: NumberFormat numberFormat) {
179: if (numberFormat != null) {
180: Assert.notNull(text, "Text must not be null");
181: Assert
182: .notNull(targetClass,
183: "Target class must not be null");
184: try {
185: Number number = numberFormat.parse(text.trim());
186: return convertNumberToTargetClass(number, targetClass);
187: } catch (ParseException ex) {
188: throw new IllegalArgumentException(ex.getMessage());
189: }
190: } else {
191: return parseNumber(text, targetClass);
192: }
193: }
194:
195: /**
196: * Decode a {@link java.math.BigInteger} from a {@link String} value.
197: * Supports decimal, hex and octal notation.
198: * @see BigInteger#BigInteger(String, int)
199: */
200: private static BigInteger decodeBigInteger(String value) {
201: int radix = 10;
202: int index = 0;
203: boolean negative = false;
204:
205: // Handle minus sign, if present.
206: if (value.startsWith("-")) {
207: negative = true;
208: index++;
209: }
210:
211: // Handle radix specifier, if present.
212: if (value.startsWith("0x", index)
213: || value.startsWith("0X", index)) {
214: index += 2;
215: radix = 16;
216: } else if (value.startsWith("#", index)) {
217: index++;
218: radix = 16;
219: } else if (value.startsWith("0", index)
220: && value.length() > 1 + index) {
221: index++;
222: radix = 8;
223: }
224:
225: BigInteger result = new BigInteger(value.substring(index),
226: radix);
227: return (negative ? result.negate() : result);
228: }
229:
230: }
|