How should I cast for Java generic with multiple bounds?

后端 未结 5 649
野的像风
野的像风 2020-12-10 01:55

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

I have a method like:

public static  void doSomet         


        
5条回答
  •  北海茫月
    2020-12-10 02:25

    As a workaround, you could define another interface FooBar that extends Foo and Bar and have your class implement that. It doesn't even have to be a top-level interface - you can declare it private if you don't want to clutter up or retrofit the rest of your code:

    private interface FooBar extends Foo, Bar {}
    public void problemFunction (Object o) {
      if ( o instanceof Foo && o instanceof Bar) {
          doSomething((FooBar) o);
      }
    }
    

提交回复
热议问题