I'm looking for a phrase that forces the checking for null values before passing them through to an object and then when the object has been called that the first thing that is checked in the method that within the object is to check for null pointer exception.

I came across the phrase before

Could you help?

Sorry guys that I have not clarified my question.

I had came across in a book before where they had mentioned a phrase where before calling a method there was checking where to prevent the passing of null pointers and the first thing that is done in the called method is to check for null pointers.

有帮助吗?

解决方案 3

Just before creating you object, you could check the params using the word assert, i.e :

assert yourValue != null

By default, assertions are disabled at runtime. To enable them, pass the option -enableassertions (or -ea) to the JVM.

Another possibility (since Java 7) is to use the method requireNonNull direclty in your constructor/method, here's an example with the constructor :

public Foo(Bar bar, Baz baz) {
     this.bar = Objects.requireNonNull(bar, "bar must not be null");
     this.baz = Objects.requireNonNull(baz, "baz must not be null");
 }

Otherwise as @Woot4Moo said you could just use an if statement.

其他提示

defensive coding is the practice.

public void go(String s)  
{  
    if(null == s)  
        //do something
    else
    //  normal execution.
}  

Null pointer exception is showing up when you have some object which is not initialized (default value of non-initialized object is null).

Thats mean, if you want to check wether object is null or not, you should use comparison operator. like:

if (object == null) {
    // do something
}

In theory any instance method of Object would work, though there's not a stand-out one for being cheap. The two most likely would be theReference.hashCode() and theReference.equals(theReference) (or maybe theReference.equals(null). Java standards require that any method call be evaluated for effect, so these calls would not be eliminated by the compiler or JITC.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top