简体   繁体   English

将方法的泛型作为泛型类泛型

[英]Pass method's generic as generic class generic

I'm querying JSON object from a service, where pagination is being used. 我正在使用正在使用分页的服务查询JSON对象。 I wanted to create a generic class, and a generic method where the values are decoded to the corresponding type, then I ran into a problem where I couldn't pass the method's generic as another generic type's generic. 我想创建一个泛型类,以及将值解码为相应类型的泛型方法,然后我遇到了一个问题,我无法将该方法的泛型作为另一个泛型类型的泛型传递。

Consider the following classes and methods: 请考虑以下类和方法:

PageResponse.class PageResponse.class

public class PageResponse<T> {
    @JsonProperty("values")
    private List<T> values;
    @JsonProperty("next")
    private String next;
}

and the method 和方法

public void fetchAllFoos(String url, AsyncResp resp) {
    this.<Foo>fetchAllPage(url, new ArrayList<Foo>(), resp);
}

public void fetchAllBars(String url, AsyncResp resp) {
    this.<Bar>fetchAllPage(url, new ArrayList<Bar>(), resp);
}

private <T> void fetchAllPage(String next, List<T> results, AsyncResp resp) {
    TypeReference<PageResponse<T>> valueTypeRef = new TypeReference<PageResponse<T>>() {
    };
    client.makeGetRequest(next, e -> {
        PageResponse<T> page = Json.mapper.readValue(e.toString(), valueTypeRef);
        results.addAll(page.getValues());
        if (page.getNext() != null) {
            fetchAllPage(page.getNext(), results, resp);
        } else {
            resp.returnValue(results);
        }
    });
}

The code compiles fine, and it works except that, the TypeReference 's generic type is PageRequest<T> instead of PageRequest<Foo> or PageRequest<Bar> and that leads me to PageResponse.values treated as List<Object> . 代码编译很好,它的工作原理除外, TypeReference的泛型类型是PageRequest<T>而不是PageRequest<Foo>PageRequest<Bar> ,这导致我将PageResponse.values视为List<Object>

I'm not looking for other kind of implementation for the problem, I'm just curious about this behavior. 我不是在为这个问题寻找其他类型的实现,我只是对这种行为感到好奇。 Is the generics evaulated in compile time, or what causes this behavior, and can it be solved? 仿制药是否在编译时间内被评估,或者是什么原因引起了这种行为,是否可以解决?

What you see here is type erasure . 你在这里看到的是类型擦除 In a nutshell, generic types are for compile time only. 简而言之,泛型类型仅用于编译时。 After compilation, the byte code won't have this information anymore. 编译后,字节代码将不再具有此信息。

Your solution is perfect. 你的解决方案很完美。 It's called a type token . 它被称为类型令牌 You can find it in java lib too, eg at EnumMap : 你也可以在java lib中找到它,例如在EnumMap

EnumMap<MyEnum, String> map = new EnumMap<>(MyEnum.class);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM