tags:

views:

75

answers:

2

Is it possible to specify both upper and lower bound constraints on type parameters in Java?

I found a conversation in Sun's forum in which this issue was discussed (apparently before the generics feature was finalized), but there was no final answer.

In summary, is there a valid syntax to do this:

public class MyClass<T extends Number super Integer>

?

+3  A: 

I don't believe so - as far as I can tell from the language specification, "super" is only valid for wildcard types in the first place. The syntax for wildcards also suggests you can only have one wildcard bound, too - so you can't use something like this either:

// Invalid
void foo(List<? extends Foo super Bar> list)

Even though both of these are okay:

// Valid
void foo(List<? extends Foo> list)

// Valid
void foo(List<? super Bar> list)
Jon Skeet
Thanks for your answer. May I suggest that you add a comment saying that the code is not valid, so that nobody thinks (falsely) that it's valid? (e.g. if it appears in a search engine results page)
Hosam Aly
@Hosam: Will do.
Jon Skeet
A: 

I haven't tried, but in theory this should work..

public <T extends Number & T super Integer> void foo(T t) {
    System.out.println("Type:" + t.getClass().getSimpleName());
}
Enno Shioji
This gave me a compile error when I tried it just now. :-(
Joe Carnahan
Tried myself right now.. Doesn't work. Sorry, I should have at least tried before posting it...
Enno Shioji