我应该如何为具有多个边界的 Java 泛型进行转换? [英] How should I cast for Java generic with multiple bounds?

查看:28
本文介绍了我应该如何为具有多个边界的 Java 泛型进行转换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以将 Java 中的对象转换为组合泛型类型?

Is it possible to cast an object in Java to a combined generic type?

我有一个类似的方法:

public static <T extends Foo & Bar> void doSomething(T object) {
    //do stuff
}

如果我有一个实现了两个接口(Foo & Bar)的类,调用这个方法是没有问题的.

Calling this method is no problem if I have a class that implements both interfaces (Foo & Bar).

问题是当我需要调用这个方法时,我需要传递给它的对象被接收为 java.lang.Object 并且我需要转换它以使编译器满意.但我不知道如何制作这个演员表.

The problem is when I need to call this method the object I need to pass to it is received as java.lang.Object and I need to cast it to make the compiler happy. But I can't figure out how to make this cast.

问题在于这样的函数:

public void problemFunction (Object o) {
  if ( o instanceof Foo && o instanceof Bar) {
      doSomething((Problematic cast) o);
  }
}

}

推荐答案

Java 8 引入了 带附加边界的投射.您可以将 Object 转换为具有多个 interfaces(或多个 interfaces)的 class.

Java 8 introduces the possibility of casting with additional bounds. You can cast an Object as a class with multiple interfaces (or just as multiple interfaces).

所以:

doSomething((Problematic cast) o);

简单地变成这样:

doSomething((Foo & Bar) o);

这篇关于我应该如何为具有多个边界的 Java 泛型进行转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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