2

Let's start with a code example, ideally, I would like it was possible to do this.

Since MyOtherClass is a generic

class MyOtherClass<Z>{}

I would like to get the Z of MyOtherClass

class C<T extends MyOtherClass<Z>> {
    Z myTypeOfReturnMethod() { return doStuff(); }
}

Unfortunately, as far as I know, I cannot specify , and the only valid grammar would be

class C<T extends MyOtherClass> {
    ???MyOtherClass.Z??? myTypeOfReturnMethod() { return doStuff(); }
}

What is the nicest way to do this? C could have two generics, but it is kind of repetitive and error prone.

Vogel612
  • 5,620
  • 5
  • 48
  • 73
M4rk
  • 2,172
  • 5
  • 36
  • 70

1 Answers1

3

The "simple" solution is to tell java about the additional type-constraint by explicitly introducing it like so:

class C<Z, T extends MyOtherClass<Z>> {
    // ...
}

While this means something one could perceive as redundancy in your typedeclarations, at least you actually get what you want ...

Everything else is semantically not supported by Java, mostly because the Z you have in the TypeBound of T is not accessible as a Type Parameter (in the sense of JLS 8.1.2), but is a TypeBound. The place you want to use Z in doesn't yet know about Z, because that hasn't been clearly introduced as a Type Parameter and gets erased. This is especially evidenced by the fact that a compile-error occurs even when the signature of myTypeOfReturnMethod is changed to Object. The result still is:

error: cannot find symbol
  class C<T extends MyOtherClass<Z>> {
                                 ^
symbol:   class Z

In addition to that the thing you most probably actually want is something "even more redundant" (cough), namely:

class C<Z, T extends MyOtherClass<? extends Z>> {

which is actually very different from the one above for reasons outlined in quite some SO questions and the JLS ...

Vogel612
  • 5,620
  • 5
  • 48
  • 73
  • 2
    I don't see why this would be redundant. – shmosel Apr 10 '17 at 23:39
  • @shmosel adjusted formulation and added some more information ;) – Vogel612 Apr 10 '17 at 23:48
  • 3
    Still don't think it's very redundant. And I wouldn't recommend `? extends Z` unless it's clear that `Z` is (only) a producer, per [PECS](http://stackoverflow.com/questions/2723397/what-is-pecs-producer-extends-consumer-super). – shmosel Apr 10 '17 at 23:52