Java: correlating type parameters

Suppose we have two common Java interfaces: Foo<T> and Bar<T> , of which there can be many implementations. Suppose we want to keep one of them in the same class, using the same value for T , but we keep the exact versions:

 public interface FooBar<T, TFoo extends Foo<T>, TBar extends Bar<T>> { TFoo getFoo(); TBar getBar(); } 

Above, T used for the sole purpose of ensuring that the TFoo and TBar use the same type parameter. Adding this type parameter to FooBar seems redundant for two reasons:

  • FooBar doesn't care about T .
  • Even so, T can be deduced from TFoo and TBar .

Therefore, my question is that there is a way to enforce such conditions without cluttering the list of parameters of type FooBar . I need to write FooBar<String, StringFoo, StringBar> instead of the theoretically equivalent FooBar<StringFoo, StringBar> .

+7
java generics type-parameter
source share
1 answer

Unfortunately, there is no better way ... The compiler needs a type T that will be declared for its use, and there is no other place to declare it:

EDIT: Unrelated Link

If the A binding is not specified first, you get a compile-time error:

  class D <T extends B & A & C> { /* ... */ } // compile-time error 

( extract from this document ) Strike>

And that's a bit of a topic, but this document defines type parameter naming conventions as single, capital letters.

+2
source share

All Articles