简体   繁体   English

空指针异常

[英]Nullpointer exception

There is a possiblity that this may be a dupicate question.这可能是一个重复的问题。 I initialize a String variable to null.I may or may not update it with a value.Now I want to check whether this variable is not equal to null and whatever I try I get a null pointer exception.I can't afford to throw nullpointer exception as it is costly.Is there any workaround that is efficient.TIA我将一个字符串变量初始化为 null。我可能会也可能不会用一个值更新它。现在我想检查这个变量是否不等于 null,无论我尝试什么我都会得到一个空指针异常。我不能抛出空指针异常,因为它很昂贵。是否有任何有效的解决方法。TIA

If you use如果你使用

if (x == null)

you will not get a NullPointerException .不会得到NullPointerException

I suspect you're doing:我怀疑你在做:

if (x.y == null)

which is throwing because x is null, not because xy is null.抛出是因为x为空,而不是因为xy为空。

If that doesn't explain it, please post the code you're using to test for nullity.如果这不能解释它,请发布您用来测试无效性的代码。

I guess you are doing something like this,我猜你正在做这样的事情,

  String s = null;

  if (s.equals(null))

You either check for null like this你要么像这样检查 null

  if (s == null)

A better approach is to ignore the null and just check for the expected value like this,更好的方法是忽略 null 并像这样检查预期值,

  if ("Expected value".equals(s))

In this case, the result is always false when s is null.在这种情况下,当 s 为 null 时,结果始终为 false。

String is immutable字符串是不可变的

@Test(expected = NullPointerException.class)
public void testStringEqualsNull() {
    String s = null;
    s.equals(null);
}

@Test
public void testStringEqualsNull2() {
    String s = null;
    TestCase.assertTrue(s == null);
}

I am comparing s==null only我只比较 s==null

can you show the code snippet that you have written s==null will never throw a NPE你能展示你写的代码片段吗 s==null 永远不会抛出 NPE

if you are checking whether "s" is null, then do not apply a dot(.) after "s".如果您正在检查“s”是否为空,则不要在“s”之后应用点(.)。 Doing that would throw NullPOinterException, as applying dot(.) means that you are trying to access on a pointer location which is basically null at the moment !这样做会抛出 NullPOinterException,因为应用 dot(.) 意味着您正在尝试访问目前基本上为 null 的指针位置!

Also try to use library functions that check whether a string is null or empty.还可以尝试使用检查字符串是 null 还是空的库函数。 you may use StringUtils.isEmpty(s) from apache library which checked both您可以使用 apache 库中的 StringUtils.isEmpty(s),它检查了两者

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

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