Xtroce
Xtroce

Reputation: 1826

Is it possible to use an extended formal type parameter in java

I try to accomplish to use the generic type parameter I used for an inner extended interface within a method

e.g.

public interface IA<T> {
    void someMethod(T);
}

public interface IB<T> {
    T anotherMethod();
}

class AImpl<T extends IB<SomeGenericTypeIWantToUse>> implements IA<T> {

   ISomeModule<SomeGenericTypeIWantToUse> module;

   public void someMethod(T param) {
        SomeGenericTypeIWantToUse myVariable = param.anotherMethod();
        module.digest(myVariable);
   }
}

public interface ISomeModule<T> {
    void digest(T value);
}

public class SomeModuleImpl<T> implements ISomeModule<T> {
    public void digest(T value) {
        //...do something...
    }
}

if instead of using SomeGenericTypeIWantToUse I use a defined type e.g. String everything works just peachy but with the generic the symbol cannot be resolved.

How would i accomplish that?

Upvotes: 0

Views: 30

Answers (1)

bashnesnos
bashnesnos

Reputation: 816

You need to specify the generic type you want to use inside the generic declaration like that:

   class AImpl<T extends IB<SomeGenericTypeIWantToUse>, SomeGenericTypeIWantToUse> implements IA<T> {

    ISomeModule<SomeGenericTypeIWantToUse> module;

    public void someMethod(T param) {
        SomeGenericTypeIWantToUse myVariable = param.anotherMethod();
        module.digest(myVariable);
    }
}

Because you're specifying a generic compiler needs to know about it explicitly, otherwise it tries to resolve it as a real class (so when you use String, it works nicely because it can resolve String).

Upvotes: 1

Related Questions