Java 检查返回值是否不为空,如果是,则在一行中使用一个方法调用分配它
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29537639/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check if returned value is not null and if so assign it, in one line, with one method call
提问by Continuity8
Java is littered with statements like:
Java 中充斥着以下语句:
if(cage.getChicken() != null) {
dinner = cage.getChicken();
} else {
dinner = getFreeRangeChicken();
}
Which takes two calls to getChicken()
before the returned object can be assigned to dinner
.
getChicken()
在将返回的对象分配给 之前,需要两次调用dinner
。
This could also be written in one line like so:
这也可以像这样写在一行中:
dinner = cage.getChicken() != null? cage.getChicken() : getFreeRangeChicken();
But alas there are still two calls to getChicken()
.
但可惜仍然有两个调用getChicken()
.
Of course we could assign a local variable then use the ternary operator again to assign it if it is not null, but this is two lines and not so pretty:
当然,我们可以分配一个局部变量,然后再次使用三元运算符来分配它,如果它不为空,但这是两行而不是那么漂亮:
FutureMeal chicken = cage.getChicken();
dinner = chicken != null? chicken : getFreeRangeChicken();
So is there any way to say:
那么有没有什么办法可以说:
Variable var = some value if some value is not null OR some other value;
变量 var = 某个值,如果某个值不为空或其他值;
And I guess I'm just talking syntax here, after the code is compiled it probably doesn't make much difference how the code was written in a performance sense.
而且我想我只是在这里谈论语法,在代码编译后,从性能角度来看,代码的编写方式可能没有太大区别。
As this is such common code it'd be great to have a one-liner to write it.
由于这是如此常见的代码,最好有一个单行代码来编写它。
Do any other languages have this feature?
其他语言有这个功能吗?
采纳答案by dasblinkenlight
Java lacks coalesce operator, so your code with an explicit temporary is your best choice for an assignment with a single call.
Java 缺少合并运算符,因此带有显式临时代码的代码是使用单个调用进行赋值的最佳选择。
You can use the result variable as your temporary, like this:
您可以将结果变量用作临时变量,如下所示:
dinner = ((dinner = cage.getChicken()) != null) ? dinner : getFreeRangeChicken();
This, however, is hard to read.
然而,这很难阅读。
回答by crashxxl
dinner = cage.getChicken();
if(dinner == null) dinner = getFreeRangeChicken();
or
或者
if( (dinner = cage.getChicken() ) == null) dinner = getFreeRangeChicken();
回答by Loki
Using Java 1.8 you can use Optional
使用 Java 1.8,您可以使用 Optional
public class Main {
public static void main(String[] args) {
//example call, the methods are just dumb templates, note they are static
FutureMeal meal = getChicken().orElse(getFreeRangeChicken());
//another possible way to call this having static methods is
FutureMeal meal = getChicken().orElseGet(Main::getFreeRangeChicken); //method reference
//or if you would use a Instance of Main and call getChicken and getFreeRangeChicken
// as nonstatic methods (assume static would be replaced with public for this)
Main m = new Main();
FutureMeal meal = m.getChicken().orElseGet(m::getFreeRangeChicken); //method reference
//or
FutureMeal meal = m.getChicken().orElse(m.getFreeRangeChicken()); //method call
}
static Optional<FutureMeal> getChicken(){
//instead of returning null, you would return Optional.empty()
//here I just return it to demonstrate
return Optional.empty();
//if you would return a valid object the following comment would be the code
//FutureMeal ret = new FutureMeal(); //your return object
//return Optional.of(ret);
}
static FutureMeal getFreeRangeChicken(){
return new FutureMeal();
}
}
You would implement a logic for getChicken
to return either Optional.empty()
instead of null, or Optional.of(myReturnObject)
, where myReturnObject
is your chicken
.
您将实现一个逻辑getChicken
以返回Optional.empty()
而不是 null 或Optional.of(myReturnObject)
,myReturnObject
您的chicken
.
Then you can call getChicken()
and if it would return Optional.empty()
the orElse(fallback)
would give you whatever the fallback would be, in your case the second method.
然后你可以打电话getChicken()
,如果它会返回Optional.empty()
,orElse(fallback)
会给你任何后备,在你的情况下是第二种方法。
回答by shan
Alternatively in Java8 you can use Nullableor NotNullAnnotations according to your need.
或者,在 Java8 中,您可以根据需要使用Nullable或NotNullAnnotations。
public class TestingNullable {
@Nullable
public Color nullableMethod(){
//some code here
return color;
}
public void usingNullableMethod(){
// some code
Color color = nullableMethod();
// Introducing assurance of not-null resolves the problem
if (color != null) {
color.toString();
}
}
}
public class TestingNullable {
public void foo(@NotNull Object param){
//some code here
}
...
public void callingNotNullMethod() {
//some code here
// the parameter value according to the explicit contract
// cannot be null
foo(null);
}
}
回答by jhyot
Same principle as Loki's answer but shorter. Just keep in mind that shorter doesn't automatically mean better.
与 Loki 的回答原理相同,但更短。请记住,较短并不自动意味着更好。
dinner = Optional.ofNullable(cage.getChicken())
.orElse(getFreerangeChicken());
Note: This usage of Optional
is explicitly discouraged by the architects of the JDK and the designers of the Optional feature. You are allocating a fresh object and immediately throwing it away every time. But on the other hand it can be quite readable.
注意:Optional
JDK 的架构师和 Optional 功能的设计者明确反对这种用法。您每次都在分配一个新对象并立即将其丢弃。但另一方面,它的可读性很强。
回答by Pieter De Bie
If you're not on java 1.8 yet and you don't mind to use commons-lang you can use org.apache.commons.lang3.ObjectUtils#defaultIfNull
如果你还没有使用 java 1.8 并且你不介意使用 commons-lang 你可以使用org.apache.commons.lang3.ObjectUtils#defaultIfNull
Your code would be:
您的代码将是:
dinner = ObjectUtils.defaultIfNull(cage.getChicken(),getFreeRangeChicken())
回答by Levite
Use your own
用你自己的
public static <T> T defaultWhenNull(@Nullable T object, @NonNull T def) {
return (object == null) ? def : object;
}
Example:
例子:
defaultWhenNull(getNullableString(), "");
Advantages
好处
- Works if you don't develop in Java8
- Works for android development with support for pre API 24devices
- Doesn't need an external library
- 如果您不使用 Java8 进行开发,则可以使用
- 适用于 Android 开发,支持API 24 之前的设备
- 不需要外部库
Disadvantages
缺点
Always evaluates the
default value
(as oposed tocond ? nonNull() : notEvaluated()
)This could be circumvented by passing a Callable instead of a default value, but making it somewhat more complicated and less dynamic (e.g. if performance is an issue).
By the way, you encounter the same disadvantage when using
Optional.orElse()
;-)
始终评估
default value
(与 相对cond ? nonNull() : notEvaluated()
)这可以通过传递一个 Callable 而不是默认值来规避,但使其更复杂和更不动态(例如,如果性能是一个问题)。
顺便说一句,您在使用时遇到了同样的缺点
Optional.orElse()
;-)
回答by user1803551
Since Java 9 you have Objects#requireNonNullElsewhich does:
从 Java 9 开始,你有Objects#requireNonNullElse它可以:
public static <T> T requireNonNullElse(T obj, T defaultObj) {
return (obj != null) ? obj : requireNonNull(defaultObj, "defaultObj");
}
Your code would be
你的代码是
dinner = Objects.requireNonNullElse(cage.getChicken(), getFreeRangeChicken());
Which is 1 line and calls getChicken()
only once, so both requirements are satisfied.
这是 1 条线路并且getChicken()
只调用一次,因此满足两个要求。
Note that the second argument cannot be null
as well; this method forces non-nullness of the returned value.
请注意,第二个参数不能null
一样;此方法强制返回值的非空性。
Consider also the alternative Objects#requireNonNullElseGet:
还要考虑替代Objects#requireNonNullElseGet:
public static <T> T requireNonNullElseGet(T obj, Supplier<? extends T> supplier)
which does not even evaluate the second argument if the first is not null
, but does have the overhead of creating a Supplier
.
如果第一个参数不是,它甚至不评估第二个参数null
,但确实有创建Supplier
.
回答by Lokesh Agrawal
How about this?
这个怎么样?
dinner = cage.getChicken();
if(dinner == null) {
dinner = getFreeRangeChicken();
}
This approach removes the else part.
这种方法删除了 else 部分。