/** Invokes <code>parseObject</code> on <code>f</code>, returning its value. */ Object stringToValue(String text, Format f) throws ParseException { if (f == null) { return text; } return f.parseObject(text); }
/** * Parse a string <code>sourceStr</code> against the pattern specified to the MessageFormat * constructor. * * @param sourceStr the string to be parsed. * @param pos the current parse position (and eventually the error position). * @return the array of parsed objects sorted according to their argument number in the pattern. */ public Object[] parse(String sourceStr, ParsePosition pos) { // Check initial text. int index = pos.getIndex(); if (!sourceStr.startsWith(leader, index)) { pos.setErrorIndex(index); return null; } index += leader.length(); Vector results = new Vector(elements.length, 1); // Now check each format. for (int i = 0; i < elements.length; ++i) { Format formatter = null; if (elements[i].setFormat != null) formatter = elements[i].setFormat; else if (elements[i].format != null) formatter = elements[i].format; Object value = null; if (formatter instanceof ChoiceFormat) { // We must special-case a ChoiceFormat because it might // have recursive formatting. ChoiceFormat cf = (ChoiceFormat) formatter; String[] formats = (String[]) cf.getFormats(); double[] limits = (double[]) cf.getLimits(); MessageFormat subfmt = new MessageFormat(); subfmt.setLocale(locale); ParsePosition subpos = new ParsePosition(index); int j; for (j = 0; value == null && j < limits.length; ++j) { subfmt.applyPattern(formats[j]); subpos.setIndex(index); value = subfmt.parse(sourceStr, subpos); } if (value != null) { index = subpos.getIndex(); value = new Double(limits[j]); } } else if (formatter != null) { pos.setIndex(index); value = formatter.parseObject(sourceStr, pos); if (value != null) index = pos.getIndex(); } else { // We have a String format. This can lose in a number // of ways, but we give it a shot. int next_index = sourceStr.indexOf(elements[i].trailer, index); if (next_index == -1) { pos.setErrorIndex(index); return null; } value = sourceStr.substring(index, next_index); index = next_index; } if (value == null || !sourceStr.startsWith(elements[i].trailer, index)) { pos.setErrorIndex(index); return null; } if (elements[i].argNumber >= results.size()) results.setSize(elements[i].argNumber + 1); results.setElementAt(value, elements[i].argNumber); index += elements[i].trailer.length(); } Object[] r = new Object[results.size()]; results.copyInto(r); return r; }