Rory Harrison
Rory Harrison

Reputation: 117

Method returning varying types of object

I am making http get requests using gson and volley. My idea was to have a method return an object containing serialised JSON.

public responseHolder getRequest(){
    //Make call
    //Parse Json into JsonObject
    return responseHolder;
}

My problem is that I want the method work with different api calls returning different data. I have 3 classes designed to store 3 different calls and I want the method to return the correct type of object. Is there a method or design pattern that would help me in this scenario or should I approach it from a different angle?

Upvotes: 3

Views: 92

Answers (3)

Grey Haven
Grey Haven

Reputation: 380

You could make a superclass of the three response classes.

public class Response { ... }
public class ResponseSubClass0 extends Response{ ... }
public class ResponseSubClass1 extends Response{ ... }
public class ResponseSubClass2 extends Response{ ... }

Then just define your method as returning Response.

public Response getResponse(){
    //do stuff
    return response; //can be any of the subclass types
}

In whatever code block is using getResponse() you can use use typeof to check which one it is if you need the specifics of a particular class.

Response r = foo.getResponse();
if(r instanceof ResponseSubClass0){
    ResponseSubClass0 rsc0 = (ResponseSubClass0)r;
    //do stuff
}
else if(r instanceof ResponseSubClass1){
    ResponseSubClass1 rsc1 = (ResponseSubClass1)r;
    //do other stuff
}
else if(r instanceof ResponseSubClass2){
    ResponseSubClass2 rsc2 = (ResponseSubClass2)r;
    //do other stuff
}

You could also make Response an interface and implement it instead of extending a superclass.

Upvotes: 1

jthomperoo
jthomperoo

Reputation: 93

Maybe try this?

private String getRequest()
{
    // Make Call
    return jsonString;
}

public TypeA getA()
{
    return new Gson().fromJson(getRequest(), TypeA.class);
}

public TypeB getB()
{
    return new Gson().fromJson(getRequest(), TypeB.class);
}

public TypeC getC()
{
    return new Gson().fromJson(getRequest(), TypeC.class);
}

Upvotes: 1

goodev
goodev

Reputation: 704

Try this:

public <T> T getRequest(Class<T> clazz){
    //Make call
    //Parse Json into JsonObject
    String json = ...;
    return new Gson().fromJson(json, clazz);
}

Upvotes: 1

Related Questions