How to call a generic method with two bounds (for a single argument) if one bound needs a cast
posted 8 years ago
I want to specify two types for a method's formal parameter. That's still simple: Make it a generic method with a type parameter like <T extends MyClass & MyInterface>.
Calling that method having an expression of type MySubClass (which extends MyClass and implements MyInterface) works fine.
But how can i call the method if i have an expression of (compile-time) type MyClass which i know is also of type MyInterface? If i cast to MyInterface, the compiler does not treat it as type "MyClass & MyInterface" (like it should?), but only MyInterface.
Here's the broken code:
I want method f to work for all MyClass subclasses which implement MyInterface, so i don't want to simply declare: void f(MySubClass o).
The only solution i can think of is using an extra adapter class like this:
and change callF1 and callF2 to
Is there a better way to fix methods callF1 and callF2?