繁体   English   中英

Java:如何返回泛型类型

[英]Java: How to return a generic type

我们有一个服务调用各种 rest 端点,并将 JSON 响应转换为 object。

我们已经看到它在 java 中完成,服务可以返回泛型类型,但无法弄清楚语法。

假设我们有一堆模型用于不同的 API 响应,以及一种调用端点并返回其中一个的方法。 例如

public class MyServiceImpl implements MyService{
    @Override
    public <T> T doGet( String endpoint) { 
        :
        HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
        :
        Gson gson = new Gson();
        T model = new T();
        model = gson.fromJson(response.getBody(), model.class));
        return(model);
    }

并因此称为:

SomeModel model = myService.doGet("https://somesite.com/someendpoint")

显然,上面的代码是行不通的,因为你不能做“new T()”

httpClient 有一个内置的方法来做到这一点,而不是将响应作为字符串返回,但我们不能使用它有两个原因:

  1. 我们需要记录原始响应字符串(这必须在任何可能失败的 json object 映射之前完成)
  2. 它的“REST”,因此返回 400、404 等导致异常且没有映射的状态代码,但我们仍然需要读取 json 休止符并将其转换为 object(在这种情况下有错误字段)

正如Yuliya Sheludyakova 提到的,你不能做new T(); 因为javac由于 generics 擦除而缺少类型信息。 即使此时已知类型和构造函数,也不需要创建新的 object,因为 Gson 在反序列化时返回的 object(Yuliya Sheludyak 也提到了这一点)。

What you can do is providing the type (an instance of java.lang.reflect.Type , java.lang.Class is one of them with type-limited capabilities) to the fromJson method invocation so that Gson would deserialize the payload into an object提供的类型。

public interface IService {

    @Nullable
    <T> T doGet(@Nonnull URL url, @Nonnull Type type)
            throws IOException;

    @Nullable
    <T> T doGet(@Nonnull URL url, @Nonnull TypeToken<? extends T> typeToken)
            throws IOException;

}
final class Service
        implements IService {

    // Gson instances are thread-safe and may be expensive on instantiation
    private static final Gson gson = new Gson();

    // Unsafe: the return type T and Type type are not bound to each other
    @Nullable
    @Override
    public <T> T doGet(@Nonnull final URL url, @Nonnull final Type type)
            throws IOException {
        // Prefer not using string buffers that may be very expensive for large payloads
        // Streams are much cheaper
        try ( final JsonReader jsonReader = new JsonReader(new InputStreamReader(doGet(url))) ) {
            return gson.fromJson(jsonReader, type);
        }
    }

    // Safe: javac can detect if the return type and the type token are bound
    @Nullable
    @Override
    public <T> T doGet(@Nonnull final URL url, @Nonnull final TypeToken<? extends T> typeToken)
            throws IOException {
        // Prefer not using string buffers that may be very expensive for large payloads
        // Streams are much cheaper
        try ( final JsonReader jsonReader = new JsonReader(new InputStreamReader(doGet(url))) ) {
            // TypeToken.getType() is guaranteed to provide a correct bound type
            return gson.fromJson(jsonReader, typeToken.getType());
        }
    }

    private static <T> T doGet(@Nonnull final URL url) {
        throw new AssertionError("Stub! " + url);
    }

}

安全方法的使用示例:

private static final TypeToken<List<User>> userListTypeToken = new TypeToken<List<User>>() {};

public static void main(final String... args)
        throws IOException {
    final IService service = new Service();
    final List<User> users = service.doGet(new URL("http://localhost:8080/users"), userListTypeToken);
    for ( final User user : users ) {
        System.out.println(user);
    }
}

请注意,Spring RestTemplate、Retrofit 和其他库也是如此,并且可能值得在您的代码中使用这些库。

暂无
暂无

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

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