新聞中心
這里有您想知道的互聯網營銷解決方案
創(chuàng)新互聯鴻蒙OS教程:鴻蒙OSFormattable
Formattable

public interface FormattableFormattable 接口必須由任何需要使用 Formatter 的 's' 轉換說明符執(zhí)行自定義格式化的類來實現。 該接口允許對任意對象進行格式化的基本控制。 例如,以下類根據標志和長度限制打印出股票名稱的不同表示:
import java.nio.CharBuffer;
import java.util.Formatter;
import java.util.Formattable;
import java.util.Locale;
import static java.util.FormattableFlags.*;
...
public class StockName implements Formattable {
private String symbol, companyName, frenchCompanyName;
public StockName(String symbol, String companyName,
String frenchCompanyName) {
...
}
...
public void formatTo(Formatter fmt, int f, int width, int precision) {
StringBuilder sb = new StringBuilder();
// decide form of name
String name = companyName;
if (fmt.locale().equals(Locale.FRANCE))
name = frenchCompanyName;
boolean alternate = (f & ALTERNATE) == ALTERNATE;
boolean usesymbol = alternate || (precision != -1 && precision < 10);
String out = (usesymbol ? symbol : name);
// apply precision
if (precision == -1 || out.length() < precision) {
// write it all
sb.append(out);
} else {
sb.append(out.substring(0, precision - 1)).append('*');
}
// apply width and justification
int len = sb.length();
if (len < width)
for (int i = 0; i < width - len; i++)
if ((f & LEFT_JUSTIFY) == LEFT_JUSTIFY)
sb.append(' ');
else
sb.insert(0, ' ');
fmt.format(sb.toString());
}
public String toString() {
return String.format("%s - %s", symbol, companyName);
}
}
當與 Formatter 結合使用時,上述類為各種格式字符串生成以下輸出。
Formatter fmt = new Formatter();
StockName sn = new StockName("HUGE", "Huge Fruit, Inc.",
"Fruit Titanesque, Inc.");
fmt.format("%s", sn); // -> "Huge Fruit, Inc."
fmt.format("%s", sn.toString()); // -> "HUGE - Huge Fruit, Inc."
fmt.format("%#s", sn); // -> "HUGE"
fmt.format("%-10.8s", sn); // -> "HUGE "
fmt.format("%.12s", sn); // -> "Huge Fruit,*"
fmt.format(Locale.FRANCE, "%25s", sn); // -> " Fruit Titanesque, Inc."
格式化表對于多線程訪問不一定是安全的。 線程安全是可選的,可以由擴展和實現此接口的類強制執(zhí)行。
除非另有說明,否則將 null 參數傳遞給此接口中的任何方法都將導致拋出 NullPointerException。
方法總結
| 修飾符和類型 | 方法 | 描述 |
|---|---|---|
| void | formatTo(Formatter formatter, int flags, int width, int precision) | 使用提供的 Formatter 格式化對象。 |
方法詳情
formatTo
void formatTo(Formatter formatter, int flags, int width, int precision)
使用提供的 Formatter 格式化對象。
參數:
| 參數名稱 | 參數描述 |
|---|---|
| formatter | 格式化程序。 實現類可以調用 Formatter#out() 或 Formatter#locale() 來分別獲取此格式化程序使用的 Appendable 或 Locale。 |
| flags | 標志修改輸出格式。 該值被解釋為位掩碼。 可以設置以下標志的任意組合:FormattableFlags#LEFT_JUSTIFY、FormattableFlags#UPPERCASE 和 FormattableFlags#ALTERNATE。 如果沒有設置標志,則應用實現類的默認格式。 |
| width | 要寫入輸出的最小字符數。 如果轉換后的值的長度小于寬度,則輸出將用 ' ' 填充,直到字符總數等于寬度。 默認情況下,填充位于開頭。 如果設置了 FormattableFlags#LEFT_JUSTIFY 標志,則填充將在末尾。 如果寬度為-1,則沒有最小值。 |
| precision | 要寫入輸出的最大字符數。 精度在寬度之前應用,因此即使寬度大于精度,輸出也會被截斷為精度字符。 如果精度為 -1,則對字符數沒有明確限制。 |
Throws:
| Throw名稱 | Throw描述 |
|---|---|
| IllegalFormatException | 如果任何參數無效。 |
本文名稱:創(chuàng)新互聯鴻蒙OS教程:鴻蒙OSFormattable
網頁鏈接:http://m.5511xx.com/article/cospoih.html


咨詢
建站咨詢
