Pau
Pau

Reputation: 16106

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)?

Upvotes: 1

Views: 157

Answers (2)

Richard
Richard

Reputation: 14625

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;
    }

}

Upvotes: 3

Adrian K.
Adrian K.

Reputation: 118

I hope I understood your question correctly. To create a new instance of your generic class you need to infer the correct type arguments like this if you want your ResponseSimple<T> to contain java.lang.reflect.Type:

ResponseSimple<Type> response = new ResponseSimple<>();

So, inbetween the <> you need to add the name of the class you want to use.

Also have a look at this: https://docs.oracle.com/javase/tutorial/java/generics/types.html

//EDIT: As you said you want to infer the type arguments dynamically, what you did works fine for me. The only thing is that you forgot the diamond operator:

@Override
public Object decode(Response response, T type) throws IOException
{
   ResponseSimple<T> response = new ResponseSimple<>(); //<> in the second part

   return null;
 }

Upvotes: 0

Related Questions