I am using the GWT library. There is a base class called Widget that all Widgets inherit from. Some Widgets implement certain interfaces (for example HasText), others do not. Sometimes I wish to guarantee that something being passed as an argument to a function is of a certain class AND implements a certain interface.
For example, I wish to have a function that takes a argument X, where X is of the class type Widget AND of the interface type HasText. I wish to have this behavior because only Widgets can be added to Layout containers, and HasText specifies the complete set of behaviors that I actually need from said Widget.
In pseudocode form, it might be:
public void fx(I_AM_A_Widget_AND_IMPLEMENT_INTERFACE_HasText x){
//do stuff with x, which is guaranteed to be a Widget AND implement HasText
}
Is this in any way possible in Java? If there are multiple ways to do so, is there a preferred/better way?
You might be able to use a generic method here:
public <T extends Widget & HasText> void fx(T x)
The compiler will infer the type of T automatically, so no extra syntax when calling the method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With