标签: nullpointerexception

为什么String.valueOf(null)抛出NullPointerException?

根据文档,该方法String.valueOf(Object obj)返回:

如果参数是null,那么一个字符串等于"null"; 否则,obj.toString()返回值.

但是当我尝试这样做时怎么样:

System.out.println("String.valueOf(null) = " + String.valueOf(null));
Run Code Online (Sandbox Code Playgroud)

它会引发NPE而不是?(如果你不相信,请亲自尝试!)

    Exception in thread "main" java.lang.NullPointerException
    at java.lang.String.(Unknown Source)
    at java.lang.String.valueOf(Unknown Source)

怎么会发生这种情况?文档对我说谎吗?这是Java中的一个主要错误吗?

java null api-design overloading nullpointerexception

122
推荐指数
3
解决办法
7万
查看次数

如何更有效地使用@Nullable和@Nonnull注释?

我可以看到@Nullable@Nonnull注释可以在防止有用NullPointerException秒,但他们并不很远传播.

  • 在一个间接层之后,这些注释的有效性完全下降,所以如果你只添加一些注释,它们就不会传播得很远.
  • 由于这些注释没有得到很好的执行,因此存在假设标记的值@Nonnull不为空并因此不执行空检查的危险.

下面的代码会导致标有一个参数@Nonnullnull没有提出任何投诉.它会NullPointerException在运行时抛出.

public class Clazz {
    public static void main(String[] args){
        Clazz clazz = new Clazz();

        // this line raises a complaint with the IDE (IntelliJ 11)
        clazz.directPathToA(null);

        // this line does not
        clazz.indirectPathToA(null); 
    }

    public void indirectPathToA(Integer y){
        directPathToA(y);
    }

    public void directPathToA(@Nonnull Integer x){
        x.toString(); // do stuff to x        
    }
}
Run Code Online (Sandbox Code Playgroud)

有没有办法使这些注释更严格地执行和/或进一步传播?

java annotations nullable nullpointerexception code-standards

120
推荐指数
7
解决办法
14万
查看次数

访问onCreate()中的视图的NullPointerException

这是针对StackOverflow上经常发布的问题的规范问题.

我正在关注一个教程.我使用向导创建了一个新活动.我NullPointerException试图在我的活动中使用Views获取方法时得到.findViewById()onCreate()

活动onCreate():

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    View something = findViewById(R.id.something);
    something.setOnClickListener(new View.OnClickListener() { ... }); // NPE HERE

    if (savedInstanceState == null) {
        getSupportFragmentManager().beginTransaction()
                .add(R.id.container, new PlaceholderFragment()).commit();
    }
}
Run Code Online (Sandbox Code Playgroud)

布局XML(fragment_main.xml):

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="packagename.MainActivity$PlaceholderFragment" >

    <View
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:id="@+id/something" />

</RelativeLayout>
Run Code Online (Sandbox Code Playgroud)

java android nullpointerexception android-fragments

113
推荐指数
2
解决办法
2万
查看次数

Boolean.valueOf()有时会产生NullPointerException

我有这个代码:

package tests;

import java.util.Hashtable;

public class Tests {

    public static void main(String[] args) {

        Hashtable<String, Boolean> modifiedItems = new Hashtable<String, Boolean>();

        System.out.println("TEST 1");
        System.out.println(modifiedItems.get("item1")); // Prints null
        System.out.println("TEST 2");
        System.out.println(modifiedItems.get("item1") == null); // Prints true
        System.out.println("TEST 3");
        System.out.println(Boolean.valueOf(null)); // Prints false
        System.out.println("TEST 4");
        System.out.println(Boolean.valueOf(modifiedItems.get("item1"))); // Produces NullPointerException
        System.out.println("FINISHED!"); // Never executed
    }
}
Run Code Online (Sandbox Code Playgroud)

我的问题是我不明白为什么测试3工作正常(它打印false并且不产生NullPointerException)同时测试4抛出一个NullPointerException.正如你在测试12中看到的那样,null并且modifiedItems.get("item1")是等于和null.

Java 7和8中的行为相同.

java boolean nullpointerexception

113
推荐指数
3
解决办法
7381
查看次数

空检查链与捕获NullPointerException

Web服务返回一个巨大的XML,我需要访问它的深层嵌套字段.例如:

return wsObject.getFoo().getBar().getBaz().getInt()
Run Code Online (Sandbox Code Playgroud)

问题是getFoo(),getBar(),getBaz()可能所有的回报null.

但是,如果我null在所有情况下检查,代码将变得非常冗长且难以阅读.此外,我可能会错过某些领域的支票.

if (wsObject.getFoo() == null) return -1;
if (wsObject.getFoo().getBar() == null) return -1;
// maybe also do something with wsObject.getFoo().getBar()
if (wsObject.getFoo().getBar().getBaz() == null) return -1;
return wsObject.getFoo().getBar().getBaz().getInt();
Run Code Online (Sandbox Code Playgroud)

写作是否可以接受

try {
    return wsObject.getFoo().getBar().getBaz().getInt();
} catch (NullPointerException ignored) {
    return -1;
}
Run Code Online (Sandbox Code Playgroud)

还是会被视为反模式?

java null exception nullpointerexception custom-error-handling

108
推荐指数
4
解决办法
1万
查看次数

在javax.annotation中找不到@Nullable.*

我想用@Nullable 注释来消除NullPointerExceptions.我在网上找到了一些教程,我注意到这个注释来自包javax.annotation.Nullable; 但是当我导入它时会产生编译错误:无法找到符号

java annotations nullable nullpointerexception null-pointer

102
推荐指数
6
解决办法
10万
查看次数

为什么int num = Integer.getInteger("123")抛出NullPointerException?

以下代码抛出NullPointerException:

int num = Integer.getInteger("123");
Run Code Online (Sandbox Code Playgroud)

我的编译器是否getInteger在null上调用,因为它是静态的?这没有任何意义!

发生了什么?

java autoboxing integer api-design nullpointerexception

100
推荐指数
3
解决办法
6万
查看次数

Eclipse/Android:"错误运行构建器'Android Pre Compiler'项目......"

尝试在Android项目上做一些工作我已经工作了几个月,但每次我尝试构建项目时,Eclipse都会抛出一个对话框说:

'Building workspace' has encountered a problem

Errors occurred during the build.
Errors running builder 'Android Pre Compiler' on project 'XXX'
java.lang.NullPointerException
Run Code Online (Sandbox Code Playgroud)

我在带有Android项目构建目标4.0.3(API级别15)的Mac上运行Eclipse,我安装了以下版本的东西

  • Eclipse - 3.7.2
  • Android开发工具 - 21.0.1
  • Android SDK - 最多17个

我已经尝试过一些东西,比如启动一个全新的工作区,安装这个"Subversive SVN JDT Ignore Extensions",升级所有内容,确保我的源文件夹(或其他任何地方)没有任何没有扩展名的文件,确保我的Java编译器是1.6并重新打开它.

编辑

以下是Eclipse错误日志中针对此问题的堆栈跟踪:

java.lang.NullPointerException
at com.android.ide.eclipse.adt.internal.build.builders.PreCompilerBuilder.build(PreCompilerBuilder.java:673)
at org.eclipse.core.internal.events.BuildManager$2.run(BuildManager.java:728)
at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42)
at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:199)
at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:239)
at org.eclipse.core.internal.events.BuildManager$1.run(BuildManager.java:292)
at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42)
at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:295)
at org.eclipse.core.internal.events.BuildManager.basicBuildLoop(BuildManager.java:351)
at org.eclipse.core.internal.events.BuildManager.build(BuildManager.java:374)
at org.eclipse.core.internal.resources.Workspace.buildInternal(Workspace.java:513)
at org.eclipse.core.internal.resources.Workspace.build(Workspace.java:432)
at org.eclipse.ui.actions.BuildAction$1.runInWorkspace(BuildAction.java:305)
at org.eclipse.core.internal.resources.InternalWorkspaceJob.run(InternalWorkspaceJob.java:38)
at org.eclipse.core.internal.jobs.Worker.run(Worker.java:54)
Run Code Online (Sandbox Code Playgroud)

会话数据:

eclipse.buildId=M20120208-0800
java.version=1.6.0_37
java.vendor=Apple Inc.
BootLoader constants: OS=macosx, ARCH=x86_64, …

eclipse android nullpointerexception adt

97
推荐指数
4
解决办法
9万
查看次数

为什么Double.parseDouble(null)和Integer.parseInt(null)抛出不同的异常?

为什么Double.parseDouble(null)和Integer.parseInt(null)抛出不同的异常?

这是历史事故还是故意的?文档清楚地说明了两种类型的例外情况Double.parseDouble(...)和一种情况Integer.parseInt(),但似乎不一致:

Integer.parseInt(null); // throws java.lang.NumberFormatException: null
Run Code Online (Sandbox Code Playgroud)

然而

Double.parseDouble(null); // throws java.lang.NullPointerException
Run Code Online (Sandbox Code Playgroud)

java exception nullpointerexception numberformatexception

90
推荐指数
2
解决办法
4万
查看次数

为什么这不会抛出NullPointerException?

以下代码的澄清说明:

StringBuilder sample = new StringBuilder();
StringBuilder referToSample = sample;
referToSample.append("B");
System.out.println(sample);
Run Code Online (Sandbox Code Playgroud)

这将打印,B以便证明samplereferToSample对象引用相同的内存引用.

StringBuilder sample = new StringBuilder();
StringBuilder referToSample = sample;
sample.append("A");
referToSample.append("B");
System.out.println(referToSample);
Run Code Online (Sandbox Code Playgroud)

这将打印AB,也证明是相同的.

StringBuilder sample = new StringBuilder();
StringBuilder referToSample = sample;
referToSample = null;
referToSample.append("A");
System.out.println(sample);
Run Code Online (Sandbox Code Playgroud)

显然这将抛出NullPointerException因为我试图调用appendnull引用.

StringBuilder sample = new StringBuilder();
StringBuilder referToSample = sample;
referToSample = null;
sample.append("A");
System.out.println(sample);
Run Code Online (Sandbox Code Playgroud)

所以这是我的问题,为什么最后一个代码示例没有抛出,NullPointerException因为我从前两个示例中看到并理解的是,如果两个对象引用同一个对象,那么如果我们更改任何值,那么它也会反映到其他,因为它们都指向相同的内存参考.那么为什么这条规则不适用于此?如果我分配null给referToSample,那么sample也应该为null,它应该抛出一个NullPointerException,但它不会抛出一个,为什么?

java reference nullpointerexception

89
推荐指数
4
解决办法
3869
查看次数