如何向上转换Java 8可选对象? [英] How to upcast Java 8 Optional objects?

查看:152
本文介绍了如何向上转换Java 8可选对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Optional对象时是否有一种有效的方法来执行upcasting。
以下是示例代码:

Is there an efficient way to perform upcasting while using an Optional object. Here is a sample code:

class A{}
class B extends A{}

B func(){
    //do something
    return new B();
}

Optional<B> func2(){
    //do something
    return Optional.of(new B());
}

main() {
    A a = func(); // Upcasting works fine
    B b = func(); // Upcasting works fine
    Optional<B> b = func2(); // 1. Upcasting works fine
    Optional<A> a = func2(); // 2. Upcasting would not work
}

(2。)给出错误。我可以通过创建另一个函数来解决它。

(2.) gives an error. I can solve it by creating another function.

但是有没有一种有效的方法,所以func2()可以用于(1.)和(2.)?

But is there an efficient way, so that func2() can be used for both (1.) and (2.) ?

推荐答案

我会写一个这样的方法:

I would write a method like this:

@SuppressWarnings("unchecked")  // Safe. See below.
static <T> Optional<T> copyOf(Optional<? extends T> opt) {
  return (Optional<T>) opt;
}

(如果你不喜欢名字 copyOf ,请参阅下面关于Guava的 ImmutableList 的评论。

(If you don't like the name copyOf, see my comment about Guava's ImmutableList below)

这在效率方面非常有效运行速度:演员在编译时被删除:

This is very efficient in terms of runtime speed: the cast gets elided at compile time:

static <T> java.util.Optional<T> copyOf(java.util.Optional<? extends T>);
    Code:
       0: aload_0  # Read the parameter.
       1: areturn  # Return the parameter.

因此唯一的成本是方法调用;这很容易被JIT消除。

so the only cost is that of a method call; this is easily done away with by the JIT.

然后你可以调用:

Optional<A> a = copyOf(func2());






这是安全的,因为可选具有以下属性:保证不会因setter方法而导致任何状态更改,这些方法的参数取决于类型变量 T 。唷。相当满口。我会更具体。


This is safe because Optional has the following property: it is guaranteed not to have any state changes caused by setter methods taking parameters dependent upon the type variable T. Phew. Quite a mouthful. I'll make it more concrete.

因为可选


  1. 没有setter方法(任何类型,但更常见的是没有采用 T 类型的参数, SomeGenericType< ; T> 等)

  2. final (因此您不能将其子类化以添加setter违反前一点)

  1. has no setter methods (of any kind, but more generally none that take parameters of type T, SomeGenericType<T> etc)
  2. is final (so you can't subclass it to add a setter to violate the previous point)

您无法对所持有的值执行任何操作< T> ; (或缺少)将使 T 的实例(或缺少它)。

there is nothing you can do to the value held by the Optional<T> (or lack thereof) that will make it not an instance of T (or lack thereof).

因为 T 的每个实例也是其超类的一个实例,所以没有什么不安全的:

And because every instance of T is also an instance of its superclasses, there is nothing unsafe about:

SuperclassOfT s = optionalOfT.get();

因此,此方法是类型安全的(如果您在非类型上调用它,它将失败-present optional;但这不是类型错误。)

As such, this method is type safe (it will fail if you've invoked it on a non-present optional; but that's not a type error).

您可以在 Guava的 ImmutableList.copyOf (上面称它为 copyOf 的灵感,即使它不是真正的副本)。在那里,的setter方法(比如 add ),但这些方法会立即抛出 UnsupportedOperationException s,因此不会影响列表的状态。

You will find similar code in Guava's ImmutableList.copyOf (the inspiration for calling it "copyOf" above, even though it's not really a copy). There, there are setter methods (like add), but those methods immediately throw UnsupportedOperationExceptions, and thus do not affect the list's state.

请注意,虽然不可变类型具有上述必要属性这样的强制安全,类型不一定需要是不可变的来安全地执行强制转换。

Note that whilst immutable types have the necessary properties described above to make such a cast safe, the type does not necessarily need to be immutable to perform the cast safely.

例如,你可以有一个 ErasableOptional< T> 类型,其上有一个 erase()方法,当被调用时,将当前值转换为缺席值(即 get()不再成功)。将此类实例强制转换为 ErasableOptional< SupertypeOfT> 是安全的,因为该值为 T 或不存在;你不能 SupertypeOfT 或缺席的实例。

For example, you could have an ErasableOptional<T> type, which has an erase() method on it which, when called, converted a "present" value into an "absent" value (i.e. get() no longer succeeds). It would be safe to cast such an instance to an ErasableOptional<SupertypeOfT> because the value is either a T or absent; you can't make it not an instance of SupertypeOfT or absent.

这篇关于如何向上转换Java 8可选对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆