java 我们可以在空对象上调用任何方法吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5855188/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 13:08:12  来源:igfitidea点击:

can we call any method on null object?

javanullmethod-call

提问by Anand

is it possible?

是否可以?

Object obj=null;

obj.someMethod();

someMethod{/*some code here*/}

回答by Matti Virkkunen

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.

您可以在空指针上调用静态方法。在静态方法调用中,指针自然会被完全忽略,但它仍然是一种情况(不查看类定义)似乎应该导致 NullPointerException 运行得很好的情况。

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

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

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.

但只是为了说清楚 - 不,您不能使用空指针调用实例方法。保护程序员免受此攻击是将 Java 等语言与 C++ 等“低级语言”区分开来的真正基本保护措施之一。它使错误能够在调用端报告,而不是在方法本身内部导致莫名其妙的段错误/诸如此类。

回答by Harry Joy

Nowe can't. it will throw NullPointerException as long as the method is not static. If method is static it will run.

不,我们不能。只要方法不是静态的,它就会抛出 NullPointerException。如果方法是静态的,它将运行。

Read this: null : Java Glossary

阅读:null : Java 术语表

回答by Don Roby

No. In Java, null is not an object.

不。在 Java 中,null 不是对象。

回答by Erhan Bagdemir

"obj" variable references to no instance on the heap. For that reason you'll get a nullpointerexception at runtime. Even your Java IDE (Eclipse, IDEA) will catch the problem and warns you about this.

“obj”变量引用堆上没有实例。因此,您将在运行时得到空指针异常。甚至您的 Java IDE(Eclipse、IDEA)也会发现问题并就此向您发出警告。

回答by aioobe

No, there is no way to call a method on a nullreference (unless the method is static!). (nulldoes not represent some "base" object, it represents a referencewhich does not point to any object at all.)

不,没有办法在null引用上调用方法(除非该方法是静态的!)。(null不代表某个“基础”对象,它代表一个根本不指向任何对象的引用。)

This works fine however (ideone.com link):

但是,这很好用(ideone.com 链接):

class MethodTest {
    static void someMethod() {
        System.out.println("Hello World");
    }
}

class Test {
    public static void main(String[] args) {
        MethodTest mt = null;
        mt.someMethod();
    }
}


Relevant quote from the JLS:

JLS的相关引述

15.12.4.4 Locate Method to Invoke
The strategy for method lookup depends on the invocation mode.

[...]

If the invocation mode is static, no target reference is needed and overriding is not allowed. Method mof class Tis the one to be invoked.

Otherwise, an instance method is to be invoked and there is a target reference. If the target reference is null, a NullPointerExceptionis thrown at this point.Otherwise, the target reference is said to refer to a target object and will be used as the value of the keyword thisin the invoked method.

[...]

15.12.4.4 定位要调用
的方法 方法查找的策略取决于调用模式。

[...]

如果调用模式是static,则不需要目标引用并且不允许覆盖。m类的方法T是要调用的方法。

否则,将调用实例方法并存在目标引用。如果目标引用为 nullNullPointerException则此时抛出a 。否则,目标引用被称为引用目标对象,并将用作this调用方法中关键字的值。

[...]

回答by loknath

yesyou can call if the method is static because static method is bound at compile time and only type of variable is used for static binding not the value of object.

是的,如果该方法是静态的,则可以调用,因为静态方法在编译时绑定,并且只有变量类型用于静态绑定,而不是对象的值。

if you try the same for non static method,get ready to catch a null pointer exception.

如果您对非静态方法尝试相同的方法,请准备好捕获空指针异常。

回答by wjans

This will always throw a NullPointerExcpetionunless someMethod is declared static. However, calling static methods on an instance is very bad practice.

NullPointerExcpetion除非将 someMethod 声明为静态,否则这将始终抛出 a 。但是,在实例上调用静态方法是非常糟糕的做法。

回答by Peter Lawrey

This won't compile as Object doesn't have someMethod(). However if you are talking about something like

这不会编译,因为 Object 没有someMethod(). 但是,如果您正在谈论类似的事情

MyClass o = null;
o.someMethod();

the answer depends on whether someMethod is static or not. If it is static, the value is ignored and it doesn't matter if its null or not.

答案取决于 someMethod 是否是静态的。如果它是静态的,则该值将被忽略,它是否为 null 无关紧要。

e.g.

例如

Thread t = null;
t.yield();

runs fine without an exception.

无一例外地运行良好。

回答by Andreas Dolk

A null objectdoes not exist. In your example, you have a variable (a pointer) that can either store a reference to an instance or nothing.

一个空的对象不存在。在您的示例中,您有一个变量(一个指针),它可以存储对实例的引用,也可以不存储。

If it doesn't point to an instance - well, then we can't use it to call methods or access fields.

如果它不指向一个实例——好吧,那么我们就不能用它来调用方法或访问字段。



wait, wait- this compiles and runs:

等待,等待- 这将编译并运行:

Math m = null;
System.out.println(m.max(1,2)); 

We can call static methods and access static fields in any variable (we just have to ignore compiler/IDE warnings!) Butthat is something different, a static method/variable is not called/accessed on the instance but on the class itself.

我们可以调用静态方法并访问任何变量中的静态字段(我们只需要忽略编译器/IDE 警告!)但这是不同的,静态方法/变量不是在实例上调用/访问,而是在类本身上调用/访问。

回答by Nirmal- thInk beYond

you cant execute

你不能执行

null.someMethod(); !!!

null.someMethod(); !!!