Assume that we have two generic Java interfaces: Foo<T>
and Bar<T>
, of which there may be many implementations. Now, assume that we want to store one of each in a single class, both using the same value for T
, but keep the exact implementations typed:
public interface FooBar<T, TFoo extends Foo<T>, TBar extends Bar<T>> {
TFoo getFoo();
TBar getBar();
}
Above, T
is used for the sole purpose of enforcing that TFoo
and TBar
's classes use the same type parameter. Adding this type parameter to FooBar
seems redundant for two reasons:
FooBar
doesn't actually care about T
at all.T
can be inferred from TFoo
and TBar
.My question is therefore if there is a way to enforce conditions like this without cluttering up FooBar
's list of type parameters. Having to write FooBar<String, StringFoo, StringBar>
instead of the theoretically equivalent FooBar<StringFoo, StringBar>
looks ugly to me.
Unfortunately, there is no better way... The compiler needs the T type to be declared in order to use it and there is no other place to declare it :
EDIT : unrelated link
If bound A is not specified first, you get a compile-time error:
class D <T extends B & A & C> { /* ... */ } // compile-time error
(extract from this doc)
And this is a little out of the subject, but this doc defines the conventions on type parameters names as being single, uppercase letters.
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