在Eclipse(4.7.2)中,将null analysis -> potential null access设置为警告。

给出以下代码:

public class Test {

    // validator method
    static boolean hasText(String s) {
        return !(s == null || s.trim().isEmpty());
    }

    public static void main(String[] args) {
        // s could come from anywhere and is null iff the data does not exist
        String s = (new Random().nextBoolean()) ? "valid" : null;
        if (hasText(s)) {
            // Potential null pointer access: The variable s may be null at this location
            System.out.println(s.length());
            // ... do actual stuff ...
        }
    }
}


如何避免潜在的空警告?由于@NotNull是有效输入,而输出是null,因此boolean将不起作用。

有没有办法告诉编译器,如果此验证方法返回true,则验证的值非空?

有没有更好的方法来处理这种验证方法?

谢谢。



为清楚起见进行更新:

数据来自用户输入(来自xml或.properties文件),如果数据确实存在,则为null。

永远不会产生null(例如,将其设置为"")会发明不存在的数据,而且我无法确切地拥有一个NullString对象(无法扩展String)来表示不存在的数据数据。

hasText(String s)必须能够接受任何输入数据,因此必须能够接受null

最佳答案

您的代码是安全的(它永远不会抛出空指针异常),但是Eclipse的分析可能太弱而无法建立该代码。您应该考虑使用功能更强大的工具。

Checker FrameworkNullness Checker可以证明您的代码是安全的。您只需要表达hasText的协定:hasText接受可能为null的参数,并且仅当其参数为非null时才返回true。

这是表达方式:

@EnsuresNonNullIf(expression="#1", result=true)
static boolean hasText(@Nullable String s) { ... }


(有关更多详细信息,请参见Javadoc for @EnsuresNonNullIf。)

这是您的完整示例,Nullness Checker会在没有警告的情况下进行验证:

import java.util.Random;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.checkerframework.checker.nullness.qual.EnsuresNonNullIf;

public class Test {

    // validator method
    @EnsuresNonNullIf(expression="#1", result=true)
    static boolean hasText(@Nullable String s) {
        return !(s == null || s.trim().isEmpty());
    }

    public static void main(String[] args) {
        // s could come from anywhere and is null iff the data does not exist
        String s = (new Random().nextBoolean()) ? "valid" : null;
        if (hasText(s)) {
            // Potential null pointer access: The variable s may be null at this location
            System.out.println(s.length());
            // ... do actual stuff ...
        }
    }
}

10-01 02:19
查看更多