如何使用param java.lang.reflect.Type在泛型类中分配赋值类型

时间:2016-08-04 06:31:41

标签: java generics

如果我有一个像这样的通用类:

public class ResponseSimple<T> {

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

然后,在其他类中我有一个方法,我需要使用此类的实例,但该方法通过param传递java.lang.reflect.Type并且它被覆盖,所以我无法更改任何方法(名称,签名......):

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

}

如何使用param类型(java.lang.reflect.Type)分配泛型类型?

2 个答案:

答案 0 :(得分:3)

我会建议这样的事情:

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

然后使用decode如下:

.decode(response, NameOfClass.class)

编辑:

如果需要扩展类,可以使用静态辅助函数:

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

并像这样使用它:

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

}

答案 1 :(得分:0)

我希望我能正确理解你的问题。 要创建泛型类的新实例,如果希望ResponseSimple<T>包含java.lang.reflect.Type,则需要推断出正确的类型参数:

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

因此,在<>之间你需要添加你想要使用的类的名称。

另请看一下:https://docs.oracle.com/javase/tutorial/java/generics/types.html

//编辑: 如你所说,你想动态地推断出类型参数,你所做的对我来说很好。唯一的问题是你忘记了钻石操作员:

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

   return null;
 }
相关问题