How should I cast for Java generic with multiple bounds?

后端 未结 5 652
野的像风
野的像风 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:29

    Unfortunately, there is no legal cast that you can make to satisfy this situation. There must be a single type known to implement all of the interfaces that you need as bounds, so that you can cast to it. The might be a type you create for the purpose, or some existing type.

    interface Baz extends Foo, Bar { }
    
    public void caller(Object w) {
      doSomething((Baz) w);
    }
    

    If other types are known, like Baz, to meet the bounds, you could test for those types, and have a branch in your caller that calls doSomething with a cast to those types. It's not pretty.

    You could also use delegation, creating your own class Baz that meets the bounds required by doSomething. Then wrap the object you are passed in an instance of your Baz class, and pass that wrapper to doSomething.

    private static class FooBarAdapter implements Foo, Bar {
      private final Object adaptee;
      FooBarAdapter(Object o) {
        adaptee = (Foo) (Bar) o;
      }
      public int flip() { return ((Foo) adaptee).flip(); }
      public void flop(int x) { ((Foo) adaptee).flop(x); }
      public void blort() { ((Bar) adaptee).blort(); }
    }
    
    public void problemFunction (Object o) {
      doSomething(new FooBarAdapter(o));
    }
    

提交回复
热议问题