使 String.format("%s", arg) 显示与“null"不同的空值参数 [英] Make String.format("%s", arg) display null-valued arguments differently from "null"

查看:125
本文介绍了使 String.format("%s", arg) 显示与“null"不同的空值参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑 bean 的自定义 toString() 实现:

Consider the custom toString() implementation of a bean:

@Override
public String toString() {
    String.format("this is %s", this.someField);
}

如果 someField 为 null,这将产生 this is null.

This yields this is null if someField is null.

有没有办法将空值参数的默认 null 字符串表示覆盖为另一个文本,即 ? 而无需显式调用 replaceAll(...)toString 方法中?

Is there a way to override the default null string representation of null-valued arguments to another text, i.e., ? without calling explicitly replaceAll(...) in the toString method?

注意:bean 继承自可以实现 Formattable (http://docs.oracle.com/javase/7/docs/api/java/util/Formattable.html) 但我似乎没有了解如何完成这项工作.

Note: The bean inherits from a superclass that could implement Formattable (http://docs.oracle.com/javase/7/docs/api/java/util/Formattable.html) but I just don't seem to understand how to make this work.

编辑:为了举例,该代码段被过度简化了,但我不是在寻找三元运算符解决方案 someField==null ??": someField 因为:

EDIT: The snippet is over-simplified for the sake of example but I'm not looking for ternary operator solutions someField==null ? "?" : someField because:

  • toString() 中可能(可能)涉及很多字段,因此检查所有字段太麻烦且不流畅.
  • 我几乎无法控制的其他人(如果有)正在编写他们自己的子类.
  • 如果一个方法被调用并返回 null,则意味着调用该方法两次或声明一个局部变量.
  • there can be (potentially) a great many fields involved in toString() so checking all fields is too cumbersome and not fluent.
  • other people whom I have little control over (if any) are writing their own subclasses.
  • if a method is called and returns null that would either imply calling the method twice or declaring a local variable.

相反,可以使用 Formattable 界面或使用一些自定义的 Formatter(顺便说一下,final)来完成任何事情吗?

Rather, can anything be done using the Formattable interface or having some custom Formatter (which is final btw.)?

推荐答案

使用 java 8,您现在可以为此使用 Optional 类:

With java 8 you can now use Optional class for this:

import static java.util.Optional.ofNullable;
...
String myString = null;
System.out.printf("myString: %s",
    ofNullable(myString).orElse("Not found")
);

这篇关于使 String.format("%s", arg) 显示与“null"不同的空值参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆