Ofer
Ofer

Reputation: 289

Referring to "nested" generic parameter in Java

Suppose I have:

class A<T> {
...
}

class B<L extends A<?>> {
...
}

Within the scope of B, is there any way to refer to the "nested" generic parameter T of the type represented by L? (not at runtime obviously)

All I could find was this, which did not answer my question.

Upvotes: 1

Views: 121

Answers (1)

Paul Boddington
Paul Boddington

Reputation: 37645

If you only occasionally need to refer to the type represented by ? it would be awkward and annoying to make it class B<T, L extends A<T>>.

What you can do instead is use generic helper methods every time you need to refer to T.

For example:

<T, L extends A<T>> void foo(L l) {
    // You can refer to both L and T here
}

Within B, if you have a variable var of type L you can do

foo((A<?>) var)

Here is a full example:

public class Example {

    static class A<T> {}

    static class B<L extends A<?>> {

        void bar(L l) {
            foo((A<?>) l);
        }
    }

    static <T, L extends A<T>> void foo(L l) {
        // You can refer to both L and T here
    }
}

Upvotes: 3

Related Questions