View Javadoc
1   /*
2    * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
3    * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4    *
5    * This code is free software; you can redistribute it and/or modify it
6    * under the terms of the GNU General Public License version 2 only, as
7    * published by the Free Software Foundation.  Oracle designates this
8    * particular file as subject to the "Classpath" exception as provided
9    * by Oracle in the LICENSE file that accompanied this code.
10   *
11   * This code is distributed in the hope that it will be useful, but WITHOUT
12   * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13   * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14   * version 2 for more details (a copy is included in the LICENSE file that
15   * accompanied this code).
16   *
17   * You should have received a copy of the GNU General Public License version
18   * 2 along with this work; if not, write to the Free Software Foundation,
19   * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20   *
21   * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22   * or visit www.oracle.com if you need additional information or have any
23   * questions.
24   */
25  
26  package java.util;
27  
28  import java.io.IOException;
29  
30  /**
31   * The <tt>Formattable</tt> interface must be implemented by any class that
32   * needs to perform custom formatting using the <tt>'s'</tt> conversion
33   * specifier of {@link java.util.Formatter}.  This interface allows basic
34   * control for formatting arbitrary objects.
35   *
36   * For example, the following class prints out different representations of a
37   * stock's name depending on the flags and length constraints:
38   *
39   * {@code
40   *   import java.nio.CharBuffer;
41   *   import java.util.Formatter;
42   *   import java.util.Formattable;
43   *   import java.util.Locale;
44   *   import static java.util.FormattableFlags.*;
45   *
46   *  ...
47   *
48   *   public class StockName implements Formattable {
49   *       private String symbol, companyName, frenchCompanyName;
50   *       public StockName(String symbol, String companyName,
51   *                        String frenchCompanyName) {
52   *           ...
53   *       }
54   *
55   *       ...
56   *
57   *       public void formatTo(Formatter fmt, int f, int width, int precision) {
58   *           StringBuilder sb = new StringBuilder();
59   *
60   *           // decide form of name
61   *           String name = companyName;
62   *           if (fmt.locale().equals(Locale.FRANCE))
63   *               name = frenchCompanyName;
64   *           boolean alternate = (f & ALTERNATE) == ALTERNATE;
65   *           boolean usesymbol = alternate || (precision != -1 && precision < 10);
66   *           String out = (usesymbol ? symbol : name);
67   *
68   *           // apply precision
69   *           if (precision == -1 || out.length() < precision) {
70   *               // write it all
71   *               sb.append(out);
72   *           } else {
73   *               sb.append(out.substring(0, precision - 1)).append('*');
74   *           }
75   *
76   *           // apply width and justification
77   *           int len = sb.length();
78   *           if (len < width)
79   *               for (int i = 0; i < width - len; i++)
80   *                   if ((f & LEFT_JUSTIFY) == LEFT_JUSTIFY)
81   *                       sb.append(' ');
82   *                   else
83   *                       sb.insert(0, ' ');
84   *
85   *           fmt.format(sb.toString());
86   *       }
87   *
88   *       public String toString() {
89   *           return String.format("%s - %s", symbol, companyName);
90   *       }
91   *   }
92   * }
93   *
94   * <p> When used in conjunction with the {@link java.util.Formatter}, the above
95   * class produces the following output for various format strings.
96   *
97   * {@code
98   *   Formatter fmt = new Formatter();
99   *   StockName sn = new StockName("HUGE", "Huge Fruit, Inc.",
100  *                                "Fruit Titanesque, Inc.");
101  *   fmt.format("%s", sn);                   //   -> "Huge Fruit, Inc."
102  *   fmt.format("%s", sn.toString());        //   -> "HUGE - Huge Fruit, Inc."
103  *   fmt.format("%#s", sn);                  //   -> "HUGE"
104  *   fmt.format("%-10.8s", sn);              //   -> "HUGE      "
105  *   fmt.format("%.12s", sn);                //   -> "Huge Fruit,*"
106  *   fmt.format(Locale.FRANCE, "%25s", sn);  //   -> "   Fruit Titanesque, Inc."
107  * }
108  *
109  * <p> Formattables are not necessarily safe for multithreaded access.  Thread
110  * safety is optional and may be enforced by classes that extend and implement
111  * this interface.
112  *
113  * <p> Unless otherwise specified, passing a <tt>null</tt> argument to
114  * any method in this interface will cause a {@link
115  * NullPointerException} to be thrown.
116  *
117  * @since  1.5
118  */
119 public interface Formattable {
120 
121     /**
122      * Formats the object using the provided {@link Formatter formatter}.
123      *
124      * @param  formatter
125      *         The {@link Formatter formatter}.  Implementing classes may call
126      *         {@link Formatter#out() formatter.out()} or {@link
127      *         Formatter#locale() formatter.locale()} to obtain the {@link
128      *         Appendable} or {@link Locale} used by this
129      *         <tt>formatter</tt> respectively.
130      *
131      * @param  flags
132      *         The flags modify the output format.  The value is interpreted as
133      *         a bitmask.  Any combination of the following flags may be set:
134      *         {@link FormattableFlags#LEFT_JUSTIFY}, {@link
135      *         FormattableFlags#UPPERCASE}, and {@link
136      *         FormattableFlags#ALTERNATE}.  If no flags are set, the default
137      *         formatting of the implementing class will apply.
138      *
139      * @param  width
140      *         The minimum number of characters to be written to the output.
141      *         If the length of the converted value is less than the
142      *         <tt>width</tt> then the output will be padded by
143      *         <tt>'&nbsp;&nbsp;'</tt> until the total number of characters
144      *         equals width.  The padding is at the beginning by default.  If
145      *         the {@link FormattableFlags#LEFT_JUSTIFY} flag is set then the
146      *         padding will be at the end.  If <tt>width</tt> is <tt>-1</tt>
147      *         then there is no minimum.
148      *
149      * @param  precision
150      *         The maximum number of characters to be written to the output.
151      *         The precision is applied before the width, thus the output will
152      *         be truncated to <tt>precision</tt> characters even if the
153      *         <tt>width</tt> is greater than the <tt>precision</tt>.  If
154      *         <tt>precision</tt> is <tt>-1</tt> then there is no explicit
155      *         limit on the number of characters.
156      *
157      * @throws  IllegalFormatException
158      *          If any of the parameters are invalid.  For specification of all
159      *          possible formatting errors, see the <a
160      *          href="../util/Formatter.html#detail">Details</a> section of the
161      *          formatter class specification.
162      */
163     void formatTo(Formatter formatter, int flags, int width, int precision);
164 }