Algirdyz
Algirdyz

Reputation: 617

Passing Class<? extends T> as a parameter

This is some code that I hope gives you an understanding of what I want. It does not work of course.

public static <T> void foo(Class<? extends T> type, AsyncCallback<T> callback){
    /*do something */
}



public void MyMethod() {
    Class a;
    if (isSomething()) {
        a = "some class";
    } else if (isSomething2()){
        a = "some other class";
    }
    /* probably more of this or even a switch*/
    useFoo(a);
}

public void useFoo(Class a){
    foo(a.class, AsyncCallback<a> {
        /* some callback */
    });
}       

Method foo is already there and I need to use it dynamically from MyMethod. Currently there is one useFoo for each different if statement in MyMethod. I want to have only one useFoo that would be called with some parameters. The reason is that the callback is a lengthy piece of code which needs to be repeated in every call for that method. How can I accomplish this without changing foo method? I hope you understand my problem. Thank you.

Upvotes: 2

Views: 5304

Answers (3)

Erwin Bolwidt
Erwin Bolwidt

Reputation: 31269

With the rest of the code the same as above, you can write your useFoo method as:

public <T> void useFoo(Class<T> a) {
    foo(a, new AsyncCallback<T>() {
        /* some callback */
    });
}

Upvotes: 0

aliteralmind
aliteralmind

Reputation: 20163

You can also declare the specific T type in a static function like this:

ClassName.<ConcreteTType>foo(tObject.class, callbackstuff);

Upvotes: 0

James Dunn
James Dunn

Reputation: 8274

I believe this is what you're looking for:

public <T> void useFoo(T a) {
    foo(a);
    // do other stuff
}

Upvotes: 1

Related Questions