Java 使 String.format("%s", arg) 显示与 "null" 不同的空值参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20404710/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 01:42:45  来源:igfitidea点击:

Make String.format("%s", arg) display null-valued arguments differently from "null"

javastringnullstring-formattingstring.format

提问by VH-NZZ

Consider the custom toString()implementation of a bean:

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

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

This yields this is nullif someFieldis null.

这将产生this is nullifsomeField为空。

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

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

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.

注意:bean 继承自一个可以实现的超类Formattablehttp://docs.oracle.com/javase/7/docs/api/java/util/Formattable.html),但我似乎不明白如何制作这项工作。

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

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

  • 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.
  • 可能(可能)涉及很多领域,toString()因此检查所有领域太麻烦且不流畅。
  • 我几乎无法控制的其他人(如果有的话)正在编写他们自己的子类。
  • 如果一个方法被调用并返回 null,这意味着调用该方法两次或声明一个局部变量。

Rather, can anything be done using the Formattableinterface or having some custom Formatter(which is finalbtw.)?

相反,可以使用Formattable界面或进行一些自定义Formatterfinal顺便说一句)来完成任何事情吗?

回答by Ruchira Gayan Ranaweera

If you don't want to use replaceAll(), You can assign a default text(String) for someField.

如果您不想使用replaceAll(),您可以为 分配一个默认文本(字符串)someField

But if some time this may assign nullagain. So you can use validation for that case

但如果有一段时间,这可能会null再次分配。所以你可以对这种情况使用验证

 this.someField == null ? "defaultText" : this.someField

回答by joey.enfield

You could just do

你可以做

String.format("this is %s", (this.someField==null?"DEFAULT":this.someField));

回答by Chris Forrence

To keep the original value of someField(in case null is a valid value), you can use a ternary operator.

要保留 的原始值someField(如果 null 是有效值),您可以使用三元运算符

String.format("This is %s", (this.someField == null ? "unknown" : this.someField));

回答by Pshemo

To avoid repeating ternary operator you can wrap it in more readable method that will check if your object is nulland return some default value if it is true like

为了避免重复三元运算符,您可以将其包装在更具可读性的方法中,该方法将检查您的对象null是否为真,如果为真则返回一些默认值,例如

static <T> T changeNull(T arg, T defaultValue) {
    return arg == null ? defaultValue : arg;
}

usage

用法

String field = null;
Integer id = null;
System.out.printf("field is %s %n", changeNull(field, ""));
System.out.printf("id is %d %n", changeNull(id, -1));
System.out.printf("id is %s %n", changeNull(field, ""));

output:

输出:

field is  
id is -1 
id is  

回答by JM Lord

A bit late on the subject, but this could be a quite clean-looking solution : First, create your own format method...

在这个主题上有点晚了,但这可能是一个看起来很干净的解决方案:首先,创建自己的格式方法......

private static String NULL_STRING = "?";

private static String formatNull(String str, Object... args){
    for(int i = 0; i < args.length; i++){
        if(args[i] == null){
            args[i] = NULL_STRING;
        }
    }

    return String.format(str, args);
}

Then, use it as will...

然后,随意使用它......

@Test
public void TestNullFormat(){
    Object ob1 = null;
    Object ob2 = "a test";

    String str = formatNull("this is %s", ob1);
    assertEquals("this is ?", str);

    str = formatNull("this is %s", ob2);
    assertEquals("this is a test", str);
}

This eliminates the need for multiple, hard-to-read, ternary operators.

这消除了对多个难以阅读的三元运算符的需要。

回答by JavaThunderFromDownunder

The nicest solution, in my opinion, is using Guava's Objects method, firstNonNull. The following method will ensure you will print an empty string if someField is ever null.

在我看来,最好的解决方案是使用 Guava 的 Objects 方法 firstNonNull。如果 someField 为空,以下方法将确保您将打印一个空字符串。

String.format("this is %s", MoreObjects.firstNonNull(this.someField, ""));

Guava docs.

番石榴文档

回答by Dmitry Klochkov

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

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

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

回答by Klitos Kyriacou

For a Java 7 solution that doesn't require external libraries:

对于不需要外部库的 Java 7 解决方案:

String.format("this is %s", Objects.toString(this.someField, "?"));

回答by eebb88

public static String format(String format, Object... args){
    for (int i=0;i<args.length;i++){
        if (args[i]==null) args[i]="";
    }
    return String.format(format,args);
}

then use the method ,ok

然后用这个方法,ok

回答by Bob Rivers

From java 7, you can use Objects.toString(Object o, String nullDefault).

从 Java 7 开始,您可以使用Objects.toString(Object o, String nullDefault).

Applied to your example: String.format("this is %s", Objects.toString(this.someField, "?"));

应用于您的示例: String.format("this is %s", Objects.toString(this.someField, "?"));