简体   繁体   English

测试返回字符串是否为 Java 中的 null 的最佳方法

[英]The best way to test if a returned string is null in Java

I have a function that concatenate a set of strings like this:我有一个 function 连接一组这样的字符串:

StringBuffer sb = new StringBuffer();

sb.append(fct1());
sb.append(fct2());
sb.append(fct3());

Where fct1(), fct2() and fct3() should return a String.其中 fct1()、fct2() 和 fct3() 应该返回一个字符串。 The problem is that I must test the returned values like this:问题是我必须像这样测试返回的值:

sb.append(fct1() == null ? "" : fct1());

because I get an exception if the value is null.因为如果值为 null,我会得到一个异常。

The problem is that I have many instructions like this and, above all, I can't modify these functions that return the strings(fct1, fct2 and fct3).问题是我有很多这样的指令,最重要的是,我无法修改这些返回字符串的函数(fct1、fct2 和 fct3)。

Is there a solution that will "sanitize" automatically my strings?有没有一种解决方案可以自动“清理”我的字符串?

Thank you.谢谢你。

PS: I created a function that can do it: PS:我创建了一个 function 可以做到:

public String testNullity(String aString){
aString == null ? "" : aString;
}

so that I can call it like this:这样我就可以这样称呼它:

sb.append(testNullity(fct1));
sb.append(testNullity(fct2));
...

Another alternative might be另一种选择可能是

 public class SafeStringBuilder  {
    private StringBuilder builder = new StringBuilder();

    public SafeStringBuilder append(String s) {
        if (s != null) 
            builder.append(s);
        return this;
    }
 }

If you don't mind introducing a dependency, use Guava 's Joiner instead of StringBuffer :如果您不介意引入依赖项,请使用GuavaJoiner而不是StringBuffer

Joiner j = Joiner.on("").skipNulls();
StringBuilder sb = new StringBuilder();
j.appendTo(sb, fct1());
j.appendTo(sb, fct2());
j.appendTo(sb, fct3());
String result = sb.toString();

// or even just
Joiner j = Joiner.on("").skipNulls();
String result = j.join(fct1(), fct2(), fct3());

NB In general, unless you need StringBuffer 's thread safety, you should use StringBuilder instead.注意 一般来说,除非您需要StringBuffer的线程安全,否则您应该使用StringBuilder Same API, better performance.同样的API,性能更好。

There is nothing whatsoever you can do to make this solution simpler except shortening the method name.除了缩短方法名称之外,您无法做任何事情来简化此解决方案。 (There might be a solution using aspect-oriented programming, but on the whole I don't really consider that simpler.) (可能有一个使用面向方面编程的解决方案,但总的来说我并不认为这更简单。)

Unfortunately your solution with testNullity() is the best you can get with Java (consider better naming though).不幸的是,您使用testNullity()的解决方案是使用 Java 可以获得的最佳解决方案(尽管考虑更好的命名)。 In fact, there is already a method that does that: StringUtils.html#defaultString .事实上,已经有一种方法可以做到这一点: StringUtils.html#defaultString

You can create your own wrapper around StringBuffer :您可以围绕StringBuffer创建自己的包装器:

class MyStringBuffer {
    StringBuffer _sb = new StringBuffer();
    public boolean append(String s) {
        _sb.append(s==null ? "" : s);
        return s == null;
    }
    public String toString() { return _sb.toString(); }
}

There is no such function in the standard API, though some methods (which do other things) have it built in.标准 API 中没有这样的 function,尽管某些方法(可以做其他事情)内置了它。

For example, System.getProperty() has a variant which takes a default value, and if it can't find the given property, it will not return null , but the given default value.例如, System.getProperty()有一个变量,它采用默认值,如果找不到给定的属性,它将不会返回null ,而是返回给定的默认值。 You might think of providing your fct* methods with such a "default" argument, if it makes sence.如果有意义的话,您可能会考虑为您的fct*方法提供这样的“默认”参数。

I think C# has a ??我认为 C# 有一个?? operator which does about what you want (you would call sb.append(fct2()?? "") ), but I suppose Java will not add any new operators soon.与您想要的操作符(您会调用sb.append(fct2()?? "") ),但我想 Java 不会很快添加任何新的操作符。

A better variant of your checking function would be this:您检查 function 的更好变体是:

public void appendIfNotNull(StringBuffer sb, String s) {
    if(s != null) {
       sb.append(s);
    }
}

This avoids the superfluous append call with an empty string if there is nothing to append.如果 append 没有任何内容,这可以避免使用空字符串进行多余的 append 调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM