代码之家  ›  专栏  ›  技术社区  ›  Vladimir

智能Java格式化程序

  •  0
  • Vladimir  · 技术社区  · 15 年前

        StringBuffer buffer = new StringBuffer();
        Formatter formatter = new Formatter(buffer);
        formatter.format("hello %1$s, %2$s and %3$s", "me", "myself", "I");
    

    $s

    我当然可以定义自己的类,比如说接受一个字符串 "hello $1, $2 and $3 ,用( $1 %1$s )并调用 toString() 对于所有参数,但我确信已经开发出更好的解决方案。

    在某个地方,在某个罐子里。。。

    编辑

    String out = MySpecialFormatter.format("hello $1, $2 and $3", "me", "myself", "I");
    

    3 回复  |  直到 15 年前
        1
  •  3
  •   Community CDub    8 年前

    有时候答案就在那里。。。

    import static java.text.MessageFormat.format;
    
    String out = format("hello {0}, {1} and {2}", "me", "myself", "2", "3");
    

    是的, Anon 很显然,Sun认为所有的程序员都那么懒惰。

        2
  •  2
  •   Anon.    15 年前

    问题是,如果您在格式上犯了错误(例如,您忘记了$s),将抛出一个异常。在格式化错误消息时,这并不是我真正想要的(因为它不在应用程序的常规路径中,可能不会被测试)。

    解决办法是 . 最好是在你写的时候。

    如果您坚持要掩盖错误代码并假装它不存在,您可以执行以下操作:

    public class LazyProgrammersFormatter {
        private Formatter _f;
    
        public LazyProgrammersFormatter(Formatter f) {
            _f = f;
        }
    
        public bool format(/*can't be bothered looking up the varargs signature, you know what it is*/) {
            try {
                _f.format(/*etc.*/);
                return true;
            } catch (FormatException e) {
                return false;
            }
        }
    }
    
        3
  •  1
  •   Teja Kantamneni    15 年前