How should I cast for Java generic with multiple bounds?

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

    It is possible to "up-cast" to a union type, by the horrible means of encoding the union type into a method's type parameter; for your example you can write

    private  Q upcast(final Object in) {
        return (Q) in;
    }
    
    // ... elsewhere...
    
    if (myObject instanceof Foo && myObject instanceof Bar) {
        doSomething(upcast(myObject));
    }
    

提交回复
热议问题