日期:2014-05-20  浏览次数:20765 次

java中Number类的intValue方法是在何处被实现的?
本帖最后由 wang_19800105 于 2014-04-28 09:44:42 编辑

import java.text.DecimalFormat;
import java.text.ParseException;

//此类的目得是用来验证1个数是不是在给定的范围内
public class DecimalFormatTest {
    public static void main(String args[]){
        boolean bl = DecimalFormatTest.isValidDate("100", 1, 100); 
        System.out.println(bl);
    }
    private static DecimalFormat numberFormat = new DecimalFormat();
    public static boolean isValidDate(String numberString,int min,int max){
        Integer validInteger = null;
        try{
        Number aNumber = numberFormat.parse(numberString);
        int anInt = aNumber.intValue(); //此方法在Number中是抽象的,为什么可以使用,是何处被实现的?
        if(anInt>=min && anInt<=max){
            validInteger = anInt; 

        }
        }catch(ParseException e){
            //Ignore and return null;
        }
        return validInteger != null;
    }
}

------解决方案--------------------
numberFormat.parse(numberString);的返回值应该是个具体类,查看一下?
------解决方案--------------------
parse(String source) 调用的是parse(String source, ParsePosition parsePosition) ,而该方法返回的是详细的具体类,以下是DecimalFormat.parse(String source, ParsePosition parsePosition)的源代码

public Number More ...parse(String text, ParsePosition pos) {
        // special case NaN
        if (text.regionMatches(pos.index, symbols.getNaN(), 0, symbols.getNaN().length())) {
            pos.index = pos.index + symbols.getNaN().length();
            return new Double(Double.NaN);
        }

        boolean[] status = new boolean[STATUS_LENGTH];
        if (!subparse(text, pos, positivePrefix, negativePrefix, digitList, false, status)) {
            return null;
        }

        // special case INFINITY
        if (status[STATUS_INFINITE]) {
            if (status[STATUS_POSITIVE] == (multiplier >= 0)) {
                return new Double(Double.POSITIVE_INFINITY);
            } else {
                return new Double(Double.NEGATIVE_INFINITY);
            }
        }

        if (multiplier == 0) {
            if (digitList.isZero()) {
                return new Double(Double.NaN);
            } else if (status[STATUS_POSITIVE]) {
                return new Double(Double.POSITIVE_INFINITY);
            } else {
                return new Double(Double.NEGATIVE_INFINITY);
            }
        }

        if (isParseBigDecimal()) {
            BigDecimal bigDecimalResult = digitList.getBigDecimal();

            if (multiplier != 1) {
                try {
                    bigDecimalResult = bigDecimalResult.divide(getBigDecimalMultiplier());