mercredi 21 octobre 2015

How can I return a super class instance?

I have an api that could have a timeout problem.

The main api method is like this :

public <T extends ApiResponse> T sendMessageSync(final Class<T> expected, final ApiBase apiMsg)

And I am using this method like this :

public <T extends ApiResponse> T send(final Class<T> expected, final ApiBase apiMsg)
{
    return sendMessageSync(expected, username, apiMsg);
}

And then :

public UsersAdmin.GetResponse getUser(final String authToken, final long userId)
{
    return send(UsersAdmin.GetResponse.class, new UsersAdmin.GetRequest(authToken, userId));
}

As you can guess, the UsersAdmin.GetResponse class is declared like that :

public class GetResponse extends ApiBase.ApiResponse

My problem : The ApiResponse class have a status attribute. When I have a timeout, I want to return a new instance of the ApiResponsewith this attribute set a specific value of an enum, like that :

if(result == null)
{
    // we didn't receive response, api timeout
    result = new ApiResponse(CR.API_TIMEOUT);
}

The problem if that fact there is a class cast exception between UsersAdmin.GetResponse and ApiResponse as I want to return a new instance of ApiResponse and this class is a super class of UsersAdmin.GetResponse.

To solved that I want to try to use reflection, but I can't access the constructors of ApiResponse from UsersAdmin.GetResponse class.

How can I acheive that ?





Aucun commentaire:

Enregistrer un commentaire