xmcx
xmcx

Reputation: 356

a generics method how to invoke another Generics method

I have two generics methods like:

<T extends MyClass> T methodA(Class<T> clazz){
...
methodB(clazz);//it is wrong
}

<T extends MyClass> T methodB(Class<T> clazz){
...
}

and I want invoke methodB in methodA, but it does not work. Is there anything I missed?

Upvotes: 0

Views: 62

Answers (1)

Sridhar
Sridhar

Reputation: 1553

I think you are missing the return statement. You declared the method returns a object of type T extending class MyClass. But, you have not returned it.

The following code block works for me.

public class CodePlay {

    public static void main(String[] args) {
        CodePlay cp = new CodePlay();
        System.out.println(cp.methodA(null));
    }

    public <T extends MyClass> T methodA(Class<T> clazz){
        // do stuff
        return methodB(clazz);
    }

    public <T extends MyClass> T methodB(Class<T> clazz) {
        // do stuff
        return null;
        // return actual value
    }

}

class MyClass {
    // do stuff
}

Upvotes: 1

Related Questions