在Java中使用空对象访问静态字段
下面的简单代码段工作正常,正在使用null对象访问静态字段在Java中使用空对象访问静态字段,java,Java,下面的简单代码段工作正常,正在使用null对象访问静态字段 final class TestNull { public static int field=100; public TestNull temp() { return(null); } } public class Main { public static void main(String[] args) { System.out.println(new
final class TestNull
{
public static int field=100;
public TestNull temp()
{
return(null);
}
}
public class Main
{
public static void main(String[] args)
{
System.out.println(new TestNull().temp().field);
}
}
在上面的代码中,语句
System.out.println(newtestnull().temp().field)
中,静态字段字段与空对象关联new TestNull().temp()
,但它仍然返回一个正确的值,即100,而不是在Java中引发空指针异常!为什么?与常规成员变量相反,静态变量属于类而不是类的实例。因此,它工作的原因很简单,因为访问静态字段不需要实例
事实上,如果访问一个静态字段会抛出一个NullPointerException
,我会说这会让我更加惊讶
如果您感到好奇,下面是查找您的程序的字节码:
// Create TestNull object
3: new #3; //class TestNull
6: dup
7: invokespecial #4; //Method TestNull."<init>":()V
// Invoke the temp method
10: invokevirtual #5; //Method TestNull.temp:()LTestNull;
// Discard the result of the call to temp.
13: pop
// Load the content of the static field.
14: getstatic #6; //Field TestNull.field:I
它编译、执行和打印:
乔科鲁阿山
与常规成员变量相反,静态变量属于类,而不属于类的实例。因此,它工作的原因很简单,因为访问静态字段不需要实例 事实上,如果访问一个静态字段会抛出一个
NullPointerException
,我会说这会让我更加惊讶
如果您感到好奇,下面是查找您的程序的字节码:
// Create TestNull object
3: new #3; //class TestNull
6: dup
7: invokespecial #4; //Method TestNull."<init>":()V
// Invoke the temp method
10: invokevirtual #5; //Method TestNull.temp:()LTestNull;
// Discard the result of the call to temp.
13: pop
// Load the content of the static field.
14: getstatic #6; //Field TestNull.field:I
它编译、执行和打印:
乔科鲁阿山
静态变量在类的每个对象之间共享。因此,虽然您返回的实际对象引用为null(在C++:TestNull*temp=null;),但您有一个TestNull类型的对象,Java可以使用它来查找该类的静态值
请记住,在Java中,对象实际上是指针。指针有一个类型。从这种类型中,Java可以识别某些信息,即使它指向null。静态变量在类的每个对象之间共享。因此,虽然您返回的实际对象引用为null(在C++:TestNull*temp=null;),但您有一个TestNull类型的对象,Java可以使用它来查找该类的静态值
请记住,在Java中,对象实际上是指针。指针有一个类型。从这种类型中,Java可以识别某些信息,即使它指向null。静态字段与类关联,而不是该类的实例。因此,访问静态字段不需要对象的实例
您也可以通过调用TestNull来访问该字段。字段静态字段与类关联,而不是该类的实例。因此,访问静态字段不需要对象的实例 您还可以通过调用TestNull.field来访问该字段@see:mably duplicate of@see:mably duplicate of