问题描述
public class Test {
public static void main(String[] args) {
Platform1 p1=Platform1.FACEBOOK; //giving NullPointerException.
Platform2 p2=Platform2.FACEBOOK; //NO NPE why?
}
}
enum Platform1{
FACEBOOK,YOUTUBE,INSTAGRAM;
Platform1(){
initialize(this);
};
public void initialize(Platform1 platform){
switch (platform) {
//platform is not constructed yet,so getting `NPE`.
//ie. we doing something like -> switch (null) causing NPE.Fine!
case FACEBOOK:
System.out.println("THIS IS FACEBOOK");
break;
default:
break;
}
}
}
enum Platform2{
FACEBOOK("fb"),YOUTUBE("yt"),INSTAGRAM("ig");
private String displayName;
Platform2(String displayName){
this.displayName=displayName;
initialize(this);
};
public void initialize(Platform2 platform){
switch (platform.displayName) {
//platform not constructed,even No `NPE` & able to access its properties.
//switch (null.displayName) -> No Exception Why?
case "fb":
System.out.println("THIS IS FACEBOOK");
break;
default:
break;
}
}
}
任何人都可以解释为什么那里是 NullPointerException
在 Platform1
中,但不在 Platform2
中。在第二种情况下,我们如何能够访问枚举对象及其属性,甚至在构造对象之前?
Can anyone explain me why there is NullPointerException
in Platform1
but not in Platform2
. How in the second case we are able to access the enum object and its properties, even before the object is constructed?
推荐答案
确切地说。正如@PeterS在正确构造之前提到的那样使用枚举导致NPE,因为在未构造的枚举上调用了values()方法。
Exactly. Just as @PeterS mentioned using enum before it has been properly constructed is causing NPE, because values() method is being called on un-constructed enum.
还有一点,我想在此处添加 Platform1
和 Platform2
两者都试图在switch()中使用未构造的枚举,但是NPE是仅在 Platform1
中。这背后的原因如下: -
One more point, I would like to add here that Platform1
and Platform2
both are trying to use unconstructed enum in switch() but NPE is only in Platform1
. Reason behind this is as follows :-
public void initialize(Platform1 platform){
switch (platform) {
以上来自 Platform1
枚举的代码正在使用 platform
在switch中的enum对象,其中使用内部 $ SwitchMap $ Platform1 []
数组并初始化此数组 values()
使用方法,因此您获得NPE。但是在 Platform2
中,开关(platform.displayName)
是 displayName $ c的比较$ c>已经初始化并且发生了字符串比较,因此没有NPE。
Above piece of code from Platform1
enum is using platform
enum object in switch where internally $SwitchMap$Platform1[]
array is used and to initialize this array values()
method is utilized, thus you get NPE. But in Platform2
, switch (platform.displayName)
is comparison on displayName
which is already initialized and a string comparison occurs thus no NPE.
以下是反编译代码的片段: -
Following are fragments of decompiled code :-
Platform1
Platform1
static final int $SwitchMap$Platform1[] =
new int[Platform1.values().length];
Platform2
Platform2
switch ((str = platform.displayName).hashCode())
{
case 3260:
if (str.equals("fb")) {
这篇关于NullPointerException | enum构造函数中的`this`导致NPE的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!