英文:
Java switch case throwing nullPointer Exception
问题
public enum Status {
REQ("URL1"),
NOT("URL2"),
GET("URL3");
String getURL;
Status(String getURL) {
this.getURL = getURL;
}
}
And a field in my class:
private Status status;
I have a function in order to retrieve the URL based on the enum type as follows:
public String viewURL() {
switch (status) {
case REQ:
return REQ.getURL;
case NOT:
return NOT.getURL;
case GET:
return GET.getURL;
}
return null;
}
I'm encountering a NullPointerException
in this method when status
is null
.
However, when I implement the same functionality using if-statements, it works fine:
public String viewURL() {
if (status == REQ) {
return REQ.getURL;
}
if (status == NOT) {
return NOT.getURL;
}
if (status == GET) {
return GET.getURL;
}
return null;
}
Not able to understand where I'm going wrong. Any help would be really appreciated!
Any help on refactoring is also appreciated!
英文:
I have an enum declared as follows -
public enum Status {
REQ ("URL1"),
NOT ("URL2"),
GET ("URL3");
String getURL;
Status(String getURL) {
this.getURL = getURL;
}
}
And a field in my class:
private Status status;
I have a function in order to retrieve the URL based on the enum type as follows -
public String viewURL() {
switch (status) {
case REQ:
return REQ.getURL;
case NOT:
return NOT.getURL;
case GET:
return GET.getURL;
}
return null;
}
I'm encountering a NullPointerException
in this method when status
is null
.
However when I implement the same functionality using if-statements it works fine -
public String viewURL() {
if (status == REQ) {
return REQ.getURL;
}
if (status == NOT) {
return NOT.getURL;
}
if (status == GET) {
return GET.getURL;
}
return null;
}
Not able to understand where I'm going wrong. Any help would be really appreciated!
Any help on re-factoring also is appreciated!
答案1
得分: 1
这是 Optional
的理想用例:
public String viewURL() {
return Optional.ofNullable(status)
.map(s -> s.getUrl) // 仅在前一步返回非空时执行
.orElse(null); // 如果任何一步返回 null,则执行
}
英文:
This is an ideal use case for Optional
:
public String viewURL() {
return Optional.ofNullable(status)
.map(s -> s.getUrl) // only executes if previous step returns non-null
.orElse(null); // executes if any step returns null
}
答案2
得分: 0
如果viewURL方法能够访问status变量,您可以使用以下代码:
public String viewURL() {
if (status != null)
return status.getURL;
return null;
}
我认为您不必使用switch语句,因为我们最终在每种情况下都使用相同的代码。也就是说,我们在每种情况下都返回status.getURL。
这里唯一的要求是Status枚举的每个实例都具有URL。
英文:
If the viewURL method has access to the status variable, you can use this code:
public String viewURL() {
if (status != null)
return status.getURL;
return null;
}
I don't think you have to use a switch statement because we end up using the same code in every case. That is, we return status.getURL in every case.
The only requirement here is that every instance of the Status enum has a URL.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论