gpt4 book ai didi

java - 使用参数创建模板类型的新对象

转载 作者:行者123 更新时间:2023-11-30 08:03:32 24 4
gpt4 key购买 nike

我正在用java编写一些JSON解析代码,并且我有几个方法,它们之间的唯一区别是它们是否返回 JSONObjectJSONArray 。我正在尝试摆脱这个:

  private JSONArray getJsonArray(String path) throws IOException {
HttpGet httpget = new HttpGet(path);
httpget.setConfig(requestConfig);

try (CloseableHttpClient httpClient = httpClientBuilder.build()) {
try (CloseableHttpResponse result = httpClient.execute(apiHost, httpget)) {
return new JSONArray(new JSONTokener(result.getEntity().getContent()));
}
}
}

private JSONObject getJsonObject(String path) throws IOException {
HttpGet httpget = new HttpGet(path);
httpget.setConfig(requestConfig);

try (CloseableHttpClient httpClient = httpClientBuilder.build()) {
try (CloseableHttpResponse result = httpClient.execute(apiHost, httpget)) {
return new JSONObject(new JSONTokener(result.getEntity().getContent()));
}
}
}

对此(无效代码):

  private <T> get(String path, Class<T> type) throws IOException {
HttpGet httpget = new HttpGet(path);
httpget.setConfig(requestConfig);

try (CloseableHttpClient httpClient = httpClientBuilder.build()) {
try (CloseableHttpResponse result = httpClient.execute(apiHost, httpget)) {
return new T(new JSONTokener(result.getEntity().getContent()));
}
}
}

如何使用参数正确初始化 T 类型的新对象?我可以以某种方式将 T 的可能值限制为 JSONObject/JSONArray 吗?我知道<T extends Something>形式,但这两个似乎直接继承自 Object没有通用接口(interface):(

最佳答案

您可以使用反射来获取并调用匹配的构造函数(如果有),并在不存在此类构造函数时引发异常。

private <T> T get(String path, Class<T> type) throws IOException {
HttpGet httpget = new HttpGet(path);
httpget.setConfig(requestConfig);

try (CloseableHttpClient httpClient = httpClientBuilder.build()) {
try (CloseableHttpResponse result = httpClient.execute(apiHost, httpget)) {
Constructor<T> constructor = type.getConstructor(JSONTokener.class);
return constructor.newInstance(new JSONTokener(result.getEntity().getContent()));
} catch (ReflectiveOperationException e) {
throw new IllegalArgumentException("Provided result class does not accept JSONTokener parameter.");
}
}
}

请注意,这有点像 duck typing ,即您并不真正将类型限制为 JSONObjectJSONArray,而是提供相应构造函数的所有内容都可以。

关于java - 使用参数创建模板类型的新对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31519864/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com