问题
I have a static method that is intended to read JSON and Parse to a Class (specified at runtime) with ObjectMapper. I would like to return an Object of the 'N' type, but I'm getting an error about using Generics.
How can I make the following code accomplish this?
public static <N, T extends AbstractRESTApplication> N GET_PAYLOAD( T app, String urlString, REQUEST_TYPE requestType) throws JsonProcessingException, MalformedURLException, IOException, NoSuchAlgorithmException, KeyManagementException {
HttpsURLConnection con = null;
try {
RSSFeedParser.disableCertificateValidation();
URL url = new URL(urlString);
con = (HttpsURLConnection) url.openConnection();
String encoding = Base64.getEncoder().encodeToString((app.getUser() + ":" + app.getPassword()).getBytes("UTF-8"));
con.setRequestProperty("Authorization", String.format("Basic %s", encoding));
//con.setDoOutput(true);//only used for writing to.
con.setDoInput(true);
con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
con.setRequestMethod(requestType.toString());
con.setRequestProperty("User-Agent", "Java client");
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
// wr.write(val);
StringBuilder content;
try (BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()))) {
String line;
content = new StringBuilder();
while ((line = in.readLine()) != null) {
content.append(line);
content.append(System.lineSeparator());
}
System.out.println(Class.class.getName() + ".GET_PAYLOAD= " + content);
//Map Content to Class.
ObjectMapper om = new ObjectMapper();
return om.readValue(content.toString(),N);//Doesn't Like N type. How do i fix?
}
} finally {
con.disconnect();
}
}
回答1:
Java Generics are implemented using "type erasure". That means the compiler can check the type safety and the types get removed at run time.
So you can't use your type variables ("N") like that. You have to pass the actual class as an argument:
public static <N, T extends AbstractRESTApplication> N GET_PAYLOAD( T app,
String urlString, REQUEST_TYPE requestType,
Class<N> nClass) throws ... {
return om.readValue(content.toString(), nClass);
来源:https://stackoverflow.com/questions/62452365/jackson-objectmapper-in-static-method-with-generics