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
And this is a little out of the subject, but this doc defines the conventions on type parameters names as being single, uppercase letters.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.