可能吗?
Object obj=null;
obj.someMethod();
someMethod{/*some code here*/}
您可以在空指针上调用静态方法。在静态方法调用中,指针自然会被完全忽略,但在某些情况下(不查看类定义)似乎应该导致 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();
}
}
但为了清楚起见 - 不,您不能使用空指针调用实例方法。保护程序员免受这种影响是真正的基本保护措施之一,它将 Java 等语言与 C++ 等“低级语言”区分开来。它允许在调用端报告错误,而不是在方法本身内部导致莫名其妙的段错误/whatnot。
不,我们不能。只要方法不是静态的,它就会抛出 NullPointerException。如果方法是静态的,它将运行。
不,在 Java 中,null 不是对象。
“obj”变量没有引用堆上的实例。因此,您将在运行时收到空指针异常。甚至您的 Java IDE(Eclipse、IDEA)也会发现问题并警告您。
是的,如果方法是静态的,您可以调用,因为静态方法是在编译时绑定的,并且只有变量类型用于静态绑定,而不是对象的值。
如果您对非静态方法尝试相同的方法,请准备好捕获空指针异常。
This won't compile as Object doesn't have someMethod()
. However if you are talking about something like
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.
e.g.
Thread t = null;
t.yield();
runs fine without an exception.
A null object does 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!) But that is something different, a static method/variable is not called/accessed on the instance but on the class itself.
No, there is no way to call a method on a null
reference (unless the method is static!). (null
does not represent some "base" object, it represents a reference which does not point to any object at all.)
This works fine however (ideone.com link):
class MethodTest {
static void someMethod() {
System.out.println("Hello World");
}
}
class Test {
public static void main(String[] args) {
MethodTest mt = null;
mt.someMethod();
}
}
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. Methodm
of classT
is 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
, aNullPointerException
is 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 keywordthis
in the invoked method.[...]
你不能执行
null.someMethod(); !!!
NullPointerExcpetion
除非 someMethod 被声明为静态,否则这将始终抛出一个。但是,在实例上调用静态方法是非常糟糕的做法。