Get type of Generics

93 Views Asked by At

I need to get type of generic type. I've already tried following

public abstract class RetrofitRequest<RESULT> extends SpiceRequest<Response<RESULT>> {

    public RetrofitRequest(){
        super(Response<RESULT>.class); //compile time error
    }

    @Override
    public final Response<RESULT> loadDataFromNetwork() throws Exception {
        WebService webService = RestFulWebService.getRestFulWebService();
        return doInBackground(webService);
    }

    protected abstract Response<RESULT> doInBackground(WebService webService) throws Exception;

}

any idea how to get this done? thanks in advance!!!

and SpiceRequest is something like this

public abstract class SpiceRequest<RESULT> implements Comparable<SpiceRequest<RESULT>> {

    public SpiceRequest(Class<RESULT> clazz) {
        ....
    }
}

Thanks!

-supunz

2

There are 2 best solutions below

1
Lakshan Dissanayake On BEST ANSWER

solved myself with the help of RC comment

public abstract class RetrofitRequest<RESULT> extends SpiceRequest<Response<RESULT>> {

    protected RetrofitRequest(){
        super((Class<Response<RESULT>>) (Class<?>) Response.class);
    }

    @Override
    public final Response<RESULT> loadDataFromNetwork() throws Exception {
        WebService webService = RestFulWebService.getRestFulWebService();
        return doInBackground(webService);
    }

    @WorkerThread
    protected abstract Response<RESULT> doInBackground(WebService webService) throws Exception;

}

and https://coderanch.com/t/681438/java/Class-Type-List-java#3196253 just saved my day

0
Makoto On

You need to mirror your parent controller in asking for a Class<RESULT>.

public RetrofitRequest(Class<RESULT> clazz){
    super(clazz);
}

The regrettable thing is now that you have to carry that all the way down the inheritance chain, but should you want to instantiate it, you'd need to provide the class too:

RetrofitRequest<String> impl = new RetrofitRequestImpl<String>(String.class);