我们可以在null对象上调用任何方法吗

我们可以在null对象上调用任何方法吗

本文介绍了我们可以在null对象上调用任何方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能吗?

Object obj=null;

obj.someMethod();

someMethod{/*some code here*/}


推荐答案

您可以在空指针上调用静态方法。在静态方法调用中,指针自然会被完全忽略,但是当(看不到类定义)看起来应该导致NullPointerException正常运行时,它仍然是一种情况。

You can call a static method on a null pointer. The pointer will naturally be completely ignored in a static method call, but it's still a case when something that (without looking at the class definition) seemingly should cause a NullPointerException runs just fine.

class FooObject {
    public static void saySomething() {
        System.out.println("Hi there!");
    }
}

class Main {
    public static void main(String[] args) {
        FooObject foo = null;
        foo.saySomething();
    }
}

但只是为了说清楚 - 不,你可以用空指针调用实例方法。保护程序员不受此限制是将Java等语言与C ++等低级语言区别开来的真正基本保护措施之一。它可以在调用端报告错误,而不是在方法本身内部引起一个莫名其妙的段错误。

But just to make it clear - no, you can't call an instance method with a null pointer. Protecting the programmer against this is one of the really basic protections that set languages like Java apart from "lower level languages" such as C++. It enables the error to be reported at the calling end, instead of it causing an inexplicable segfault/whatnot inside the method itself.

这篇关于我们可以在null对象上调用任何方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 03:36