简体   繁体   English

Java 中的 Generics 出现问题

[英]Trouble with Generics in Java

I am using RestAssured framework for api calls and I want to create a method that will return give me value from the JSON response in the specific variable type.我正在为 api 调用使用 RestAssured 框架,并且我想创建一个方法,该方法将返回给我来自特定变量类型的 JSON 响应的值。
I want to use generic return type but I don't like me implementation.我想使用通用返回类型,但我不喜欢我的实现。
The RestAssured getList() returns a list of values according to JSON path and cast to value type. RestAssured getList() 根据 JSON 路径返回值列表并转换为值类型。 When I implement the getList() method, I have to cast the result to T in order to comply to the return value type:当我实现 getList() 方法时,我必须将结果转换为 T 以符合返回值类型:

public <T> T getValuesFromResponse(Response response, ValueTypeEnum value) {
    T t = null;
    switch (value) {
        case ID:
            //Will return List<Integer>
            t = (T) response.thenReturn().jsonPath().getList("data.id", Integer.class);
            break;
        case NAME:
            //Will return List<String>
            t = (T) response.thenReturn().jsonPath().getList("data.name", String.class);
            break;
    }
    return t;
}

When I want to call this method, I have to cast the values again to the type I need, ie:当我想调用这个方法时,我必须再次将值转换为我需要的类型,即:

((List<Integer>) getValuesFromResponse(response, ValueTypeEnum.ID)).get(0)

How do I avoid the double casting?如何避免双重铸造?
Is my implementation correct for using generic List<T> return type?我的实现对于使用泛型List<T>返回类型是否正确?

What do you think about using a method like this:您如何看待使用这样的方法:

 public <T> List<T> getValuesFromResponse(Response response, String key, Class <T> clazz) {
    return response.thenReturn().jsonPath().getList(key, clazz);
}

... and then call it as: ...然后将其称为:

List<Integer> listOfIds = getValuesFromResponse (response, "data.id", Integer.class);
List<String> listOfNames = getValuesFromResponse (response, "data.name", String.class);

I have't tried it to compile with the real 'Response' class, but I think this should work.我还没有尝试使用真正的“响应”class 进行编译,但我认为这应该可以。 Please let me know.请告诉我。

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

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