简体   繁体   English

如果对象在Java中为null,则获取默认值

[英]get default value if the object is null in Java

I am curius to know how I can write a shorter version of the following code in Java. 我很想知道如何在Java中编写以下代码的简短版本。

I have the following Java class (belongs to JAX-RS): 我有以下Java类(属于JAX-RS):

I need back the int value of the responseStatus if that possible (response is not null) otherwise default int status value needs to be returned. 如果可能,我需要返回responseStatus的int值(response不为null),否则需要返回默认的int status值。

I do not want to add any library dependency to my project just for this small piece of code. 我不想只为这小段代码向我的项目中添加任何库依赖项。

This is the code what come up in my mind first: 这是我首先想到的代码:

private static int getDefaultStatusCodeIfNull(final Response response) {
    if (Objects.isNull(response)) {
        return Response.Status.INTERNAL_SERVER_ERROR.getStatusCode();
    }

    return response.getStatus();
}

The following code is maybe shorter with lambda but it is so long and hard to read: 以下代码对于lambda可能会更短,但它是如此之长且难以阅读:

int status = Optional.ofNullable(response)
      .orElse(Response.status(Response.Status.INTERNAL_SERVER_ERROR).build()).getStatus();

Is there any shorter one line way to get this int value? 有没有一种更短的单行方式来获取此int值?

Do you think the 2nd one is better solution then the 1st? 您认为第二个是比第一个更好的解决方案吗?

使用三元运算符,也许吗?

return (response == null) ? Response.Status.INTERNAL_SERVER_ERROR.getStatusCode() : response.getStatus();

您可以使用三元运算符,该运算符可以将if / else放在一行上:

int status = (response == null) ? Response.Status.INTERNAL_SERVER_ERROR.getStatusCode() : response.getStatus();

The slightly cleaner lambda version is: 较干净的lambda版本是:

Optional.ofNullable(response).map(Response::getStatus).orElse(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode())

Though honestly, I think the ternary operator here is cleaner. 坦白地说,我认为这里的三元运算符更干净。

I would prefer your first version, as using lanbda sounds much like overkill. 我更喜欢您的第一个版本,因为使用lanbda听起来像是过分杀伤。

You could also use the ternary operator, as others have already pointed out: 您还可以使用三元运算符,正如其他人已经指出的那样:

private static int getDefaultStatusCodeIfNull(final Response response) {
    return response != null ? response.getStatus()  Response.Status.INTERNAL_SERVER_ERROR.getStatusCode();
}
int status = response==null?Response.Status.INTERNAL_SERVER_ERROR.getStatusCode():response.getStatus();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM