Pau Chorro Pau Chorro - 4 months ago 11
Java Question

How to assign assign type in a generic class with a param java.lang.reflect.Type

If I have a class with a generic like this:

public class ResponseSimple<T> {

private Map<String, Collection<String>> headers;
private int status;
private T body;
}


Then,in other class I have a method which I need to use an instance of this class, but the method passes by param a java.lang.reflect.Type and it's overrided so I can't change the any of the method (name, signature..):

public class ResponseEncoder extends GsonDecoder {

public ResponseEncoder() {
super();
}
@Override
public Object decode(Response response, Type type) throws IOException
{
//How assign type T using type param??
//┬┐ResponseSimple<T> responseSimple = new ResponseSimple();?

return null;
}

}


How could I assign the generic type T using the param type (java.lang.reflect.Type)?

Answer

I would suggest something like this:

@Override
public <T> T decode(Response response, Class<T> type) throws IOException
{
    //How assign type T using type param??
    ResponseSimple<T> response = new ResponseSimple<T>();

    return response;
}

Then use decode as follows:

.decode(response, NameOfClass.class)

Edit:

If you need to extend your class you could use a static helper function:

public static <T> ResponseSimple<T> createResponse(Class<T> clazz)
{
       return new ResponseSimple<>();
}

And use it like this:

public class ResponseEncoder extends GsonDecoder {

    public ResponseEncoder() {
        super();
    }
    @Override
    public Object decode(Response response, Type type) throws IOException
    {
        Class<?> clazz = (Class<?>) type; 
        ResponseSimple<?> response = createResonse(clazz); 

        return null;
    }

}