简体   繁体   English

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

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

I have this code: 我有以下代码:

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;
}

However when I call this function in a different class once the sprite object has been defined and initialized: 但是,当我已经定义并初始化了精灵对象时,在另一个类中调用此函数时:

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

I get a null pointer exception, pointing to the line that contains this: 我得到一个空指针异常,指向包含以下内容的行:

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

Why is this? 为什么是这样?

Check to see if image is null. 检查图像是否为空。 That's most likely where the error is coming from. 这最有可能是错误的来源。

somewhere you are creating a Sprite and passing the constructor a null image. 在某个地方创建Sprite并向构造函数传递一个空图像。 In your constructor try doing something like this 在您的构造函数中尝试做这样的事情

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

It would happen if image is null . 如果imagenull ,就会发生这种情况。 Somewhere in your code you must be making this call: 您必须在代码中的某个位置进行此调用:

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

You probably want to add some null checking in your constructor that throws a RuntimeException . 您可能想要在构造函数中添加一些引发RuntimeException null检查。 This will make it easy to find the code that is passing in a null Image . 这将使查找null Image传递的代码变得容易。

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

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