简体   繁体   English

我可以给一个这样的默认值来避免 null 指针异常吗?

[英]Can I give a default value like this to avoid null pointer exception?

Can I give variables default values such as this?我可以给变量这样的默认值吗?

public class Laptop {
    // initializing variable to avoid null pointer exception?
    private String owner = "";

    public Laptop(String owner) {
        this.owner = owner;
    }

    public String getOwner() {
        return owner;
    }

    public void setOwner(String owner) {
        this.owner = owner;
    }
}
private String owner = "";

Doing this is redundant because it's always overwritten in the constructor.这样做是多余的,因为它总是在构造函数中被覆盖。 The constructor would effectively be this:构造函数实际上是这样的:

public Laptop(String owner) {
    super();
    this.owner = "";
    this.owner = owner;
}

Clearly, the first assignment gets stomped straight away, so there's no point in doing it.显然,第一个任务会立即被踩踏,所以这样做没有意义。 Remove the initializer on the field.删除字段上的初始化程序。

If you want to be able to create a Laptop without an owner, you can provide a default value by overloading the constructor:如果您希望能够创建没有所有者的Laptop ,您可以通过重载构造函数来提供默认值:

public Laptop() {
  this("");
}

public Laptop(String owner) {
    this.owner = owner;
}

Now you can invoke like:现在你可以像这样调用:

Laptop owned = new Laptop("me"); // Will use the explicitly-provided owner "me".
Laptop unowned = new Laptop();   // Will use the default "".

If you never want owner to be null (I presume you're worried about later, when you use the result of getOwner() ), add a null check wherever you assign owner :如果您不想让owner成为 null (我想您稍后会担心,当您使用getOwner()的结果时),请在您分配owner的任何位置添加 null 检查:

this.owner = Objects.requireNonNull(owner);

This will fail with an NPE at the point of assignment, but that's a good place to fail if you never want a null -valued field: you can see exactly where that null came from, and fix that.这将在分配时出现NPE失败,但如果您从不想要null值字段,那么这是一个失败的好地方:您可以确切地看到null的来源,并修复它。

You could do something like what Andreas suggested in comments :您可以执行Andreas 在评论中建议的操作:

this.owner = (owner != null ? owner : "");

but I would recommend against this: if you want owner to be "" , that's the value you should pass into the constructor;但我建议不要这样做:如果您希望owner成为"" ,那么这就是您应该传递给构造函数的值; passing in null , if that's not an allowed value, should be made clearly incorrect by throwing an exception.传入null ,如果这不是允许的值,则应该通过抛出异常来明确不正确。 Passing in a value and having it coerced to some other value would feel surprising.传入一个值并将其强制转换为其他值会让人感到惊讶。

Where do you expect a NullPointerException ?您期望在哪里出现NullPointerException None of the code in your sample would cause an NPE, no matter if you initialise the attribute owner with the empty String, or not.无论您是否使用空字符串初始化属性owner ,示例中的任何代码都不会导致 NPE。

And when you call new Laptop(null) or Laptop.setOwner(null) , the attribute value will be overwritten, no matter which value it had before.当您调用new Laptop(null)Laptop.setOwner(null)时,属性值将被覆盖,无论它之前具有哪个值。


But yes, in general such an initialisation can be used to prevent an NPE, under the proper circumstance.但是,是的,一般来说,在适当的情况下,这种初始化可以用来防止 NPE。 Your code does not provides these circumstances …您的代码没有提供这些情况……

What you have done is fine but in order to guarantee that getOwner() will never return null you need to safeguard your set method like:您所做的很好,但为了保证getOwner()永远不会返回null您需要保护您的 set 方法,例如:

public void setOwner(String owner) {
    this.owner = owner != null ? owner : "";
}

If on the other hand, setting null should be treated as an Exception because setting this property is considered violation of your workflow:另一方面,如果设置null应被视为异常,因为设置此属性被视为违反您的工作流程:

public void setOwner(String owner) {
    if (owner == null) {
       throw new IllegalArgumentException("Unexpected owner found.");
    }
    this.owner = owner;
}

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

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