Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/share/classes/java/text/Format.java
38829 views
/*1* Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425/*26* (C) Copyright Taligent, Inc. 1996, 1997 - All Rights Reserved27* (C) Copyright IBM Corp. 1996 - 1998 - All Rights Reserved28*29* The original version of this source code and documentation is copyrighted30* and owned by Taligent, Inc., a wholly-owned subsidiary of IBM. These31* materials are provided under terms of a License Agreement between Taligent32* and Sun. This technology is protected by multiple US and International33* patents. This notice and attribution to Taligent may not be removed.34* Taligent is a registered trademark of Taligent, Inc.35*36*/3738package java.text;3940import java.io.Serializable;4142/**43* <code>Format</code> is an abstract base class for formatting locale-sensitive44* information such as dates, messages, and numbers.45*46* <p>47* <code>Format</code> defines the programming interface for formatting48* locale-sensitive objects into <code>String</code>s (the49* <code>format</code> method) and for parsing <code>String</code>s back50* into objects (the <code>parseObject</code> method).51*52* <p>53* Generally, a format's <code>parseObject</code> method must be able to parse54* any string formatted by its <code>format</code> method. However, there may55* be exceptional cases where this is not possible. For example, a56* <code>format</code> method might create two adjacent integer numbers with57* no separator in between, and in this case the <code>parseObject</code> could58* not tell which digits belong to which number.59*60* <h3>Subclassing</h3>61*62* <p>63* The Java Platform provides three specialized subclasses of <code>Format</code>--64* <code>DateFormat</code>, <code>MessageFormat</code>, and65* <code>NumberFormat</code>--for formatting dates, messages, and numbers,66* respectively.67* <p>68* Concrete subclasses must implement three methods:69* <ol>70* <li> <code>format(Object obj, StringBuffer toAppendTo, FieldPosition pos)</code>71* <li> <code>formatToCharacterIterator(Object obj)</code>72* <li> <code>parseObject(String source, ParsePosition pos)</code>73* </ol>74* These general methods allow polymorphic parsing and formatting of objects75* and are used, for example, by <code>MessageFormat</code>.76* Subclasses often also provide additional <code>format</code> methods for77* specific input types as well as <code>parse</code> methods for specific78* result types. Any <code>parse</code> method that does not take a79* <code>ParsePosition</code> argument should throw <code>ParseException</code>80* when no text in the required format is at the beginning of the input text.81*82* <p>83* Most subclasses will also implement the following factory methods:84* <ol>85* <li>86* <code>getInstance</code> for getting a useful format object appropriate87* for the current locale88* <li>89* <code>getInstance(Locale)</code> for getting a useful format90* object appropriate for the specified locale91* </ol>92* In addition, some subclasses may also implement other93* <code>getXxxxInstance</code> methods for more specialized control. For94* example, the <code>NumberFormat</code> class provides95* <code>getPercentInstance</code> and <code>getCurrencyInstance</code>96* methods for getting specialized number formatters.97*98* <p>99* Subclasses of <code>Format</code> that allow programmers to create objects100* for locales (with <code>getInstance(Locale)</code> for example)101* must also implement the following class method:102* <blockquote>103* <pre>104* public static Locale[] getAvailableLocales()105* </pre>106* </blockquote>107*108* <p>109* And finally subclasses may define a set of constants to identify the various110* fields in the formatted output. These constants are used to create a FieldPosition111* object which identifies what information is contained in the field and its112* position in the formatted result. These constants should be named113* <code><em>item</em>_FIELD</code> where <code><em>item</em></code> identifies114* the field. For examples of these constants, see <code>ERA_FIELD</code> and its115* friends in {@link DateFormat}.116*117* <h4><a name="synchronization">Synchronization</a></h4>118*119* <p>120* Formats are generally not synchronized.121* It is recommended to create separate format instances for each thread.122* If multiple threads access a format concurrently, it must be synchronized123* externally.124*125* @see java.text.ParsePosition126* @see java.text.FieldPosition127* @see java.text.NumberFormat128* @see java.text.DateFormat129* @see java.text.MessageFormat130* @author Mark Davis131*/132public abstract class Format implements Serializable, Cloneable {133134private static final long serialVersionUID = -299282585814624189L;135136/**137* Sole constructor. (For invocation by subclass constructors, typically138* implicit.)139*/140protected Format() {141}142143/**144* Formats an object to produce a string. This is equivalent to145* <blockquote>146* {@link #format(Object, StringBuffer, FieldPosition) format}<code>(obj,147* new StringBuffer(), new FieldPosition(0)).toString();</code>148* </blockquote>149*150* @param obj The object to format151* @return Formatted string.152* @exception IllegalArgumentException if the Format cannot format the given153* object154*/155public final String format (Object obj) {156return format(obj, new StringBuffer(), new FieldPosition(0)).toString();157}158159/**160* Formats an object and appends the resulting text to a given string161* buffer.162* If the <code>pos</code> argument identifies a field used by the format,163* then its indices are set to the beginning and end of the first such164* field encountered.165*166* @param obj The object to format167* @param toAppendTo where the text is to be appended168* @param pos A <code>FieldPosition</code> identifying a field169* in the formatted text170* @return the string buffer passed in as <code>toAppendTo</code>,171* with formatted text appended172* @exception NullPointerException if <code>toAppendTo</code> or173* <code>pos</code> is null174* @exception IllegalArgumentException if the Format cannot format the given175* object176*/177public abstract StringBuffer format(Object obj,178StringBuffer toAppendTo,179FieldPosition pos);180181/**182* Formats an Object producing an <code>AttributedCharacterIterator</code>.183* You can use the returned <code>AttributedCharacterIterator</code>184* to build the resulting String, as well as to determine information185* about the resulting String.186* <p>187* Each attribute key of the AttributedCharacterIterator will be of type188* <code>Field</code>. It is up to each <code>Format</code> implementation189* to define what the legal values are for each attribute in the190* <code>AttributedCharacterIterator</code>, but typically the attribute191* key is also used as the attribute value.192* <p>The default implementation creates an193* <code>AttributedCharacterIterator</code> with no attributes. Subclasses194* that support fields should override this and create an195* <code>AttributedCharacterIterator</code> with meaningful attributes.196*197* @exception NullPointerException if obj is null.198* @exception IllegalArgumentException when the Format cannot format the199* given object.200* @param obj The object to format201* @return AttributedCharacterIterator describing the formatted value.202* @since 1.4203*/204public AttributedCharacterIterator formatToCharacterIterator(Object obj) {205return createAttributedCharacterIterator(format(obj));206}207208/**209* Parses text from a string to produce an object.210* <p>211* The method attempts to parse text starting at the index given by212* <code>pos</code>.213* If parsing succeeds, then the index of <code>pos</code> is updated214* to the index after the last character used (parsing does not necessarily215* use all characters up to the end of the string), and the parsed216* object is returned. The updated <code>pos</code> can be used to217* indicate the starting point for the next call to this method.218* If an error occurs, then the index of <code>pos</code> is not219* changed, the error index of <code>pos</code> is set to the index of220* the character where the error occurred, and null is returned.221*222* @param source A <code>String</code>, part of which should be parsed.223* @param pos A <code>ParsePosition</code> object with index and error224* index information as described above.225* @return An <code>Object</code> parsed from the string. In case of226* error, returns null.227* @exception NullPointerException if <code>pos</code> is null.228*/229public abstract Object parseObject (String source, ParsePosition pos);230231/**232* Parses text from the beginning of the given string to produce an object.233* The method may not use the entire text of the given string.234*235* @param source A <code>String</code> whose beginning should be parsed.236* @return An <code>Object</code> parsed from the string.237* @exception ParseException if the beginning of the specified string238* cannot be parsed.239*/240public Object parseObject(String source) throws ParseException {241ParsePosition pos = new ParsePosition(0);242Object result = parseObject(source, pos);243if (pos.index == 0) {244throw new ParseException("Format.parseObject(String) failed",245pos.errorIndex);246}247return result;248}249250/**251* Creates and returns a copy of this object.252*253* @return a clone of this instance.254*/255public Object clone() {256try {257return super.clone();258} catch (CloneNotSupportedException e) {259// will never happen260throw new InternalError(e);261}262}263264//265// Convenience methods for creating AttributedCharacterIterators from266// different parameters.267//268269/**270* Creates an <code>AttributedCharacterIterator</code> for the String271* <code>s</code>.272*273* @param s String to create AttributedCharacterIterator from274* @return AttributedCharacterIterator wrapping s275*/276AttributedCharacterIterator createAttributedCharacterIterator(String s) {277AttributedString as = new AttributedString(s);278279return as.getIterator();280}281282/**283* Creates an <code>AttributedCharacterIterator</code> containing the284* concatenated contents of the passed in285* <code>AttributedCharacterIterator</code>s.286*287* @param iterators AttributedCharacterIterators used to create resulting288* AttributedCharacterIterators289* @return AttributedCharacterIterator wrapping passed in290* AttributedCharacterIterators291*/292AttributedCharacterIterator createAttributedCharacterIterator(293AttributedCharacterIterator[] iterators) {294AttributedString as = new AttributedString(iterators);295296return as.getIterator();297}298299/**300* Returns an AttributedCharacterIterator with the String301* <code>string</code> and additional key/value pair <code>key</code>,302* <code>value</code>.303*304* @param string String to create AttributedCharacterIterator from305* @param key Key for AttributedCharacterIterator306* @param value Value associated with key in AttributedCharacterIterator307* @return AttributedCharacterIterator wrapping args308*/309AttributedCharacterIterator createAttributedCharacterIterator(310String string, AttributedCharacterIterator.Attribute key,311Object value) {312AttributedString as = new AttributedString(string);313314as.addAttribute(key, value);315return as.getIterator();316}317318/**319* Creates an AttributedCharacterIterator with the contents of320* <code>iterator</code> and the additional attribute <code>key</code>321* <code>value</code>.322*323* @param iterator Initial AttributedCharacterIterator to add arg to324* @param key Key for AttributedCharacterIterator325* @param value Value associated with key in AttributedCharacterIterator326* @return AttributedCharacterIterator wrapping args327*/328AttributedCharacterIterator createAttributedCharacterIterator(329AttributedCharacterIterator iterator,330AttributedCharacterIterator.Attribute key, Object value) {331AttributedString as = new AttributedString(iterator);332333as.addAttribute(key, value);334return as.getIterator();335}336337338/**339* Defines constants that are used as attribute keys in the340* <code>AttributedCharacterIterator</code> returned341* from <code>Format.formatToCharacterIterator</code> and as342* field identifiers in <code>FieldPosition</code>.343*344* @since 1.4345*/346public static class Field extends AttributedCharacterIterator.Attribute {347348// Proclaim serial compatibility with 1.4 FCS349private static final long serialVersionUID = 276966692217360283L;350351/**352* Creates a Field with the specified name.353*354* @param name Name of the attribute355*/356protected Field(String name) {357super(name);358}359}360361362/**363* FieldDelegate is notified by the various <code>Format</code>364* implementations as they are formatting the Objects. This allows for365* storage of the individual sections of the formatted String for366* later use, such as in a <code>FieldPosition</code> or for an367* <code>AttributedCharacterIterator</code>.368* <p>369* Delegates should NOT assume that the <code>Format</code> will notify370* the delegate of fields in any particular order.371*372* @see FieldPosition#getFieldDelegate373* @see CharacterIteratorFieldDelegate374*/375interface FieldDelegate {376/**377* Notified when a particular region of the String is formatted. This378* method will be invoked if there is no corresponding integer field id379* matching <code>attr</code>.380*381* @param attr Identifies the field matched382* @param value Value associated with the field383* @param start Beginning location of the field, will be >= 0384* @param end End of the field, will be >= start and <= buffer.length()385* @param buffer Contains current formatted value, receiver should386* NOT modify it.387*/388public void formatted(Format.Field attr, Object value, int start,389int end, StringBuffer buffer);390391/**392* Notified when a particular region of the String is formatted.393*394* @param fieldID Identifies the field by integer395* @param attr Identifies the field matched396* @param value Value associated with the field397* @param start Beginning location of the field, will be >= 0398* @param end End of the field, will be >= start and <= buffer.length()399* @param buffer Contains current formatted value, receiver should400* NOT modify it.401*/402public void formatted(int fieldID, Format.Field attr, Object value,403int start, int end, StringBuffer buffer);404}405}406407408