繁体   English   中英

为什么这会导致空指针异常?

[英]Why does this cause a null pointer exception?

我有以下代码:

public class Sprite {
    protected float x;
    protected float y;
    protected Image image;
    protected Rectangle boundingBox;

    Sprite(float x, float y, Image image) {
        this.x = x;
        this.y = y;
        this.image = image;
        boundingBox = new Rectangle(x, y, 
            this.image.getWidth(), this.image.getHeight());
    }

...

public Rectangle getBoundingBox() {
    return boundingBox;
}

但是,当我已经定义并初始化了精灵对象时,在另一个类中调用此函数时:

public static boolean collides(Sprite object1, Sprite object2) {
    return object1.getBoundingBox().intersects(object2.getBoundingBox());
}

我得到一个空指针异常,指向包含以下内容的行:

this.image.getWidth(), this.image.getHeight());

为什么是这样?

检查图像是否为空。 这最有可能是错误的来源。

在某个地方创建Sprite并向构造函数传递一个空图像。 在您的构造函数中尝试做这样的事情

if (image == null) throw new Exception("Cannot create Sprite with null image")

如果imagenull ,就会发生这种情况。 您必须在代码中的某个位置进行此调用:

new Sprite(aFloat, anotherFloat, aNullValue); // aNullValue == null

您可能想要在构造函数中添加一些引发RuntimeException null检查。 这将使查找null Image传递的代码变得容易。

暂无
暂无

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

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