java 在java中安全地从Long对象转换为long原语的惯用方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42983242/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 06:59:40  来源:igfitidea点击:

Idiomatic way of converting from Long object to long primitive safely in java

java

提问by Dhairya Seth

I was trying to pass a Long object value to a method that expects long primitive, passing directly works except for the case when the Long object is null. In this case I get a Null Pointer Exception.

我试图将一个 Long 对象值传递给一个需要 long 原语的方法,除了 Long 对象为空的情况外,直接传递是有效的。在这种情况下,我得到一个空指针异常。

Long foo=null;
bar.methodExpects_long_primitive(foo);

I can create a check if foo is null and skip calling the method, like

我可以创建一个检查 foo 是否为空并跳过调用该方法,例如

Long foo=null;
if(foo!=null){
bar.methodExpects_long_primitive(foo);
}

or if I want to provide a default value

或者如果我想提供一个默认值

Long foo=null;
bar.methodExpects_long_primitive(foo==null?defaultValue:foo);

Is there a elegant/better way to do this? I have to repeat this multiple times in the codebase and doing it like this seems to add a lot of conditionals.

有没有一种优雅/更好的方法来做到这一点?我必须在代码库中多次重复这一点,这样做似乎会添加很多条件。

I could create my own method to do this, but I would like to know if there is already any such library method.

我可以创建自己的方法来做到这一点,但我想知道是否已经有任何这样的库方法。

采纳答案by Andy Thomas

As of Java 8, one option is to wrap your Long in an java.util.Optional. Wherever possible, pass this around instead of the Long. When you must get a long value, you can provide a default with Optional.orElse():

从 Java 8 开始,一种选择是将 Long 包装在java.util.Optional 中。在可能的情况下,传递它而不是 Long。当你必须得到一个长值时,你可以提供一个默认值Optional.orElse()

Long foo = null;

Optional<Long> optFoo = Optional.ofNullable( foo );
long longFoo = optFoo.orElse( -1L );

System.out.println( longFoo );

Or you can test whether the Optional holds a value with Optional.empty():

或者您可以测试 Optional 是否包含一个值Optional.empty()

    Long foo = null;

    Optional<Long> optFoo = Optional.ofNullable( foo );
    if ( ! optFoo.empty() ) {
        long longFoo = optFoo.get();

        System.out.println( longFoo );
    }

One nice side effect of this approach is that it is clear that the value might be null, no matter where you pass the Optional. Another is that an attempt to call get() when the value is null will throw an exception immediately.

这种方法的一个很好的副作用是很明显,无论您将 Optional 传递到何处,该值都可能为 null。另一个是当值为 null 时尝试调用 get() 会立即抛出异常。

Before Java 8,you could use Google's guava library, which provides a very similar class com.google.common.base.Optional.

在 Java 8 之前,您可以使用 Google 的 guava 库,它提供了一个非常相似的类com.google.common.base.Optional

回答by T.J. Crowder

There's nothing built into Long(e.g., some static method) to do it.

没有内置的东西Long(例如,一些静态方法)可以做到这一点。

Assuming you have multiple methods accepting longyou need to use this with, you'll probably want your own method, something along the lines of

假设您有多种方法接受long您需要使用它,您可能需要自己的方法,类似于

// On some utility class, say LongUtil
public static long val(Long l, long defaultvalue) {
    return l == null ? defaultValue : l.longValue();
}

Then

然后

bar.methodExpects_long_primitive(LongUtil.val(foo, defaultValue));

Of course, that's not a lot shorter than

当然,这并不比

bar.methodExpects_long_primitive(foo == null ? defaultValue : (long)foo);

If it's just methodExpects_long_primitive, I'd probably modify it to accept a Longinstead, and handle the nullwithin it.

如果只是methodExpects_long_primitive,我可能会修改它以接受 a Long,并null在其中处理。

回答by m.antkowicz

just change your method to get object Long and then check for null

只需更改您的方法以获取对象 Long 然后检查 null

T methodExpects_long_primitive(Long l) {
    long foo = (l != null) ? l : 0L;

If you do not owe the method you need to handle null out of the method as you wrote

如果您不欠方法,则需要在编写时处理方法中的 null

bar.methodExpects_long_primitive(foo==null?defaultValue:foo);