繁体   English   中英

我如何注释我的助手方法,以便Eclipse知道如果返回true,则其参数为非null?

[英]How can I annotate my helper method so Eclipse knows its argument is non null if it returns true?

我有一个辅助方法hasContent(String) ,如果其参数非空且至少包含一个非空白字符,则返回true。 我刚刚在Eclipse中启用了null分析,我发现当我使用这个方法来执行一个代码块时,这个代码块是以我的helper函数的结果为条件的,表明字符串有内容(因此不能为null),尽管如此Eclipse抱怨我的String可能仍为null。

辅助功能

public static boolean hasContent(String text) {
    if (text == null)
        return false;
    if (text.trim().length() == 0)
        return false;
    return true;
}

使用示例

...
String dataString;

try {
    dataString = readStringFromFile("somefile.txt");
} catch (IOException e) {
    System.err.println("Failed to read file due to error: " + e);
    dataString = null;
}

// At this point dataString may be null

if (hasContent(dataString)) {

    // At this point dataString must be non-null, but Eclipse warns:
    // "Potential null pointer access: The variable dataString may be null at this location"
    // at the following reference to dataString

    System.out.println("Read string length " + dataString.length());
}
...

这种情况的最佳做法是什么? 如果可以避免,我不想压制警告。 我更愿意告诉Eclipse,如果hasContent()返回true那么它的参数肯定是非null。 这可能吗? 如果是这样,怎么样?

你的方法的契约是如果hasContent返回true,那么它的参数保证是非null的。

Eclipse无法在编译时表达或检查此合同,至少在不更改代码和降低其样式的情况下。

Nullness Checker是一个不同的工具,可以在编译时表达和检查此合同。 它不需要您更改代码就可以。 您只需添加@EnsuresNonNullIf注释您的代码:

@EnsuresNonNullIf(expression="#1", result=true)
public static boolean hasContent(String text) { ...

Nullness Checker随Checker Framework一起分发。 有一个Eclipse插件 ,可以让你在Eclipse中运行Nullness Checker。

它可能不是最佳实践,但是:如果抛出IOException,则可以返回false,或者只是将变量设置为false。 如果没有,您可以将变量设置为true(在try-block中)。

try {
    dataString = readStringFromFile("somefile.txt");
    hasContent = true;
} catch (IOException e) {
    System.err.println("Failed to read file due to error: " + e);
    hasContent = false;
}

我无法看到你正在尝试的方法。

您可以修改hasContent以返回它传递的字符串,而不是boolean ,如果参数为null或为空,则抛出Exception 然后,您将使用@NonNull注释该函数。 然而,这会以我怀疑你不喜欢的方式破坏你的调用代码,因为它必须使用try / catch逻辑而不是if

这将使hasContent函数:

@NonNull
public static String hasContent(String text) throws Exception {
    if (text == null)
        throw new Exception( "Null string" );
    if (text.trim().length() == 0)
        throw new Exception( "Empty string" );
    return text;        
}

和调用代码:

...
try {
    dataString = readStringFromFile("somefile.txt");
} catch (IOException e) {
    System.err.println("Failed to read file due to error: " + e);
    dataString = null;
}

// At this point dataString may be null
try {
    dataString = validateHasContent( dataString );
    // At this point dataString must be non-null

    System.out.println("Read string length " + dataString.length());
} catch( Exception e ) {        
}
...

如果您准备做出这种妥协,那么专门的例外显然会更好。

暂无
暂无

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

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