I'm writing some JSON parsing code in java, and I've got a couple methods where the only difference between them is whether they return JSONObject
or JSONArray
. I'm trying to go from this:
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()));
}
}
}
to this (not valid code):
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()));
}
}
}
How do I properly initialize a new object of type T with parameters? Can I somehow limit the possible values of T to JSONObject / JSONArray? I know of <T extends Something>
form, but those two seem to inherit straight from Object
with no common interfaces :(