简体   繁体   中英

How to use generic types in method signature?

I have this signature

public final <T1 extends Pair<Pair<T3, T4>, Pair<T3, T4>>,
              T3 extends Enum<MyConstant>,
              T4 extends BigDecimal>
        void doSomething(final int number, final T1 pair);

I can use it like this

Pair<Pair<MyConstant, BigDecimal>, Pair<MyConstant, BigDecimal>> pair = 
    new Pair<Pair<MyConstant, BigDecimal>, Pair<MyConstant, BigDecimal>>(
        new Pair<MyConstant, BigDecimal>(const1, value1),
        new Pair<MyConstant, BigDecimal>(const2, value2));
_myObject.doSomething(1, pair);

I would like to have this signature but it does not work:

public final <T1 extends Pair<T2, T2>,
              T2 extends Pair<T3, T4>,
              T3 extends Enum<MyConstant>,
              T4 extends BigDecimal>
        void doSomething(final int number, final T1 pair);

I get this error:

Bound mismatch: The generic method doSomething(int, T1) of type
MyObject is not applicable for the arguments (int,
Pair<Pair<MyConstant,BigDecimal>,Pair<MyConstant,BigDecimal>>). The
inferred type Pair<MyConstant,BigDecimal> is not a valid substitute
for the bounded parameter <T2 extends Pair<T3,T4>>

If I understood it right what you are trying to do, this should work:

public final <T1 extends Pair<? extends Pair<? extends Enum<MyConstant>, 
                                             ? extends BigDecimal>, 
                              ? extends Pair<? extends Enum<MyConstant>, 
                                             ? extends BigDecimal>>>
    void doSomething(final int number, final T1 pair);

I just hope I got the matching braces right ;-)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM