Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I guarantee typing on an argument's class AND interface?

Tags:

java

gwt

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?

like image 477
Stephen Cagle Avatar asked Feb 19 '10 03:02

Stephen Cagle


1 Answers

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.

like image 114
Anon. Avatar answered Nov 14 '22 21:11

Anon.