簡體   English   中英

Jackson ObjectMapper 在 Static 方法與 Generics

[英]Jackson ObjectMapper in Static Method with Generics

我有一個 static 方法,旨在讀取 JSON 並使用 ObjectMapper 解析為 Class(在運行時指定)。 我想返回一個“N”類型的 Object,但在使用 Generics 時出現錯誤。

我怎樣才能讓下面的代碼完成這個?

    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();
    }

}

Java Generics 是使用“類型擦除”實現的。 這意味着編譯器可以檢查類型安全並在運行時刪除類型。

所以你不能像那樣使用你的類型變量(“N”)。 您必須將實際的 class 作為參數傳遞:

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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM