java中的自定义转换说明符

时间:2010-11-25 14:58:23

标签: java format

我希望我的数据结构是自定义格式的。 例如我有DS

Address {
    string house_number,
    string street,
    string city,
    long pin_code,
}

现在,我想将某些转换说明符与每个字段相关联。

e.g. house_number -> H
     street -> S,
     city -> C,
     pin_code -> P
     ...

所以像

这样的东西
myPrintWriter.printf("Mr A lives in %C", address_instance) 

收益“A先生住在波士顿”(如果address_instance.city = boston)等。

似乎没有简单的方法可以做到这一点。 java.util.Formatter似乎是最终的。它提供的唯一自定义是通过Formattable接口,但这有助于仅自定义's'转换说明符。 有没有办法添加我们的自定义转换说明符?任何帮助将不胜感激。

谢谢,

2 个答案:

答案 0 :(得分:3)

  

似乎没有简单的方法可以做到这一点。 java.util.Formatter似乎是最终的。

这是真的,但你仍然可以使用构图。我会做类似以下的事情:

class ExtendedFormatter {
    private Formatter defaultFormatter;

    // provide the same methods like the normal Formatter and pipe them through
    // ...

    // then provide your custom method, or hijack one of the existing ones
    // to extend it with the functionality you want
    // ...
    public Formatter format(String format, Object... args) {
         // extract format specifiers from string
         // loop through and get value from param array

         ExtendedFormattable eft = (ExtendedFormattable)args1;
         String specifierResult = eft.toFormat(formatSpecifier);  // %C would return city

         // use specifierResult for the just queried formatSpecifier in your result string
    }
}

困难的部分是知道如何将不同的格式说明符附加到要输出的字段。我能想到的第一种方法是提供您自己的ExtendedFormattable接口,每个应该与ExtendedFormatter一起使用的类可以实现,并返回自定义格式说明符的相应值。那可能是:

class Address implements ExtendedFormattable {
    public String toFormat(String formatSpecifier) { // just an very simple signature example
         // your custom return values here ...  
    }
}

还有注释,但我认为这不是一种非常可行的方式。

示例调用如下:

ExtendedFormatter ef = new ExtendedFormatter();
ef.format("Mr A lives in %C", address_instance);

答案 1 :(得分:0)

我相信你需要编写自己的格式化程序,它可以按你想要的方式工作。

相关问题