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

Java 使用参数创建模板类型的新对象,java,Java,我正在用java编写一些JSON解析代码,我有几个方法,它们之间的唯一区别是返回JSONObject还是JSONArray。我试图从这个角度出发: private JSONArray getJsonArray(String path) throws IOException { HttpGet httpget = new HttpGet(path); httpget.setConfig(requestConfig); try (CloseableHttpClient

我正在用java编写一些JSON解析代码,我有几个方法,它们之间的唯一区别是返回
JSONObject
还是
JSONArray
。我试图从这个角度出发:

  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 get(字符串路径,类类型)引发IOException{
HttpGet HttpGet=新的HttpGet(路径);
httpget.setConfig(requestConfig);
try(CloseableHttpClient-httpClient=httpClientBuilder.build()){
try(CloseableHttpResponse result=httpClient.execute(apiHost,httpget)){
返回新的T(新的JSONTokener(result.getEntity().getContent());
}
}
}

如何使用参数正确初始化T类型的新对象?我是否可以将T的可能值限制为JSONObject/JSONArray?我知道
表单,但这两个似乎直接从
对象继承而来,没有公共接口:(

您可以使用反射来获取和调用匹配的构造函数(如果有),如果不存在这样的构造函数,则引发异常

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.");
        }
    }
}
private T get(字符串路径,类类型)引发IOException{
HttpGet HttpGet=新的HttpGet(路径);
httpget.setConfig(requestConfig);
try(CloseableHttpClient-httpClient=httpClientBuilder.build()){
try(CloseableHttpResponse result=httpClient.execute(apiHost,httpget)){
Constructor=type.getConstructor(JSONTokener.class);
返回constructor.newInstance(新的JSONTokener(result.getEntity().getContent());
}捕捉(反射操作异常e){
抛出新的IllegalArgumentException(“提供的结果类不接受JSONTokener参数”);
}
}
}

请注意,这有点像,也就是说,您并没有真正将类型限制为
JSONObject
JSONArray
,而是提供相应构造函数的所有内容都是可以的。

org.json
(我假设您正在使用的就是这个)不支持泛型反序列化。请使用更复杂的方法,如Jackson或Gson。@SotiriosDelimanolis我不认为这是一个重复的问题。另一个问题基本上是“如何解析JSON”,而这是“如何创建与泛型参数对应的类的实例”,它基本上完全独立于JSON。@SotiriosDelimanolis提供的代码只是为了更好地说明我的观点。tobias_k正确地理解了我问题的本质。我现在明白了。重新打开。谢谢,这正是我想要的。考虑到我的大部分编程经验都是使用duck类型的语言,我对此很满意。m限制到
JSONObject
/
JSONArray
的思路是允许编译器推断T将始终具有正确的构造函数,而不是限制函数的调用方式。
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.");
        }
    }
}