NumberParser.java

package com.ziesemer.utils.classParser;

import java.lang.reflect.Modifier;
import java.math.BigDecimal;
import java.math.BigInteger;

/**
 * @author Mark A. Ziesemer
 * 	<a href="http://www.ziesemer.com">&lt;www.ziesemer.com&gt;</a>
 */
public class NumberParser implements IClassParser{
	
	@Override
	public Object convert(final Class<?> c, final String str) throws Exception{
		if(c.isPrimitive() || Number.class.isAssignableFrom(c)){
			String s = str;
			int radix = 10;
			
			// Temporarily remove any "-" prefix to look for following prefixes of alternate number bases...
			String prefix = "";
			if(s.startsWith("-")){
				prefix = "-";
				s = s.substring(1);
			}else if(s.startsWith("+")){
				// While we're at it, support any "+" prefixes.
				s = s.substring(1);
			}
			
			// Look for prefixes of alternate number bases, and set the alternate radix as needed...
			if(s.startsWith("0x")
					|| s.startsWith("0X")
					|| s.startsWith("0h")
					|| s.startsWith("0H")){
				radix = 16;
				s = s.substring(2);
			}else if(s.startsWith("0o")){
				radix = 8;
				s = s.substring(2);
			}
			
			// Put back any "-" prefix, if temporarily removed above.
			s = prefix + s;
			
			if(c == Byte.class || c == Byte.TYPE){
				return Byte.valueOf(s, radix);
			}
			if(c == Short.class || c == Short.TYPE){
				return Short.valueOf(s, radix);
			}
			if(c == Integer.class || c == Integer.TYPE){
				return Integer.valueOf(s, radix);
			}
			if(c == Long.class || c == Long.TYPE){
				return Long.valueOf(s, radix);
			}
			if(c == Float.class || c == Float.TYPE){
				if(radix != 10){
					throw new ClassParseException("Unrecognized value", c, str);
				}
				return Float.valueOf(s);
			}
			if(c == Double.class || c == Double.TYPE){
				if(radix != 10){
					throw new ClassParseException("Unrecognized value", c, str);
				}
				return Double.valueOf(s);
			}
			if(!c.isPrimitive()){
				if(c == BigInteger.class){
					return new BigInteger(s, radix);
				}
				if(c == BigDecimal.class){
					if(radix != 10){
						throw new ClassParseException("Unrecognized value", c, str);
					}
					return new BigDecimal(s);
				}
				if(Modifier.isAbstract(c.getModifiers())){
					if(radix != 10){
						return new BigInteger(s, radix);
					}
					return new BigDecimal(s);
				}
			}
		}
		return IClassParser.NO_RESULT;
	}
	
}