簡體   English   中英

如何將任何類型的 object 傳遞給其中包含 Class 類型的方法

[英]how to pass any type of object into a method that has Class types within it

我有一種方法可以將 model class 轉換為 883812976388 正文,用於 rest 請求,保證 rest:

public String getXmlBodyForRequest(PatchRequest model) {
    StringWriter sw = new StringWriter();

    JAXBContext jaxbContext = JAXBContext.newInstance(PatchRequest.class);
    Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
    jaxbMarshaller.setProperty(JAXB_FORMATTED_OUTPUT, TRUE);

    QName qName = new QName("com.companyname.testdata", "demo");
    JAXBElement<PatchRequest> root = new JAXBElement<>(qName, PatchRequest.class, model);

    jaxbMarshaller.marshal(root, sw);
    return sw.toString();
}

上面的代碼獲取傳遞給它的 PatchRequest,並將其轉換為 PATCH 主體的 xml。 我想擴展它以包括任何 model class 所以我嘗試使用 generics:

    public <T> String getXmlBodyForRequest(T model) {
    StringWriter sw = new StringWriter();

    JAXBContext jaxbContext = JAXBContext.newInstance(T.class);
    Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
    jaxbMarshaller.setProperty(JAXB_FORMATTED_OUTPUT, TRUE);

    QName qName = new QName("com.companyname.testdata", "demo");
    JAXBElement<T> root = new JAXBElement<>(qName, T.class, model);

    jaxbMarshaller.marshal(root, sw);
    return sw.toString();
}

但當然我不能為 JAXBContext 或 QName 輸入 T.class。 我想知道我會用什么方法讓代碼接受任何類型的 object。在此先感謝 A

您可以通過調用getClass()來獲取任何實例的 class object。 這適用於JAXBContext.newInstance

JAXBContext jaxbContext = JAXBContext.newInstance(model.getClass());

但是,不幸的是,對於new JAXBElement ,這不滿足類型檢查器的要求:

JAXBElement<T> root = new JAXBElement<>(qName, model.getClass(), model);

結果是:

cannot infer type arguments for JAXBElement<>
  reason: inference variable T has incompatible bounds
    equality constraints: capture#1 of ? extends java.lang.Object
    lower bounds: T

解決方法是讓您的getXmlBodyForRequest也需要 class 參數,就像JAXBElement構造函數一樣:

public <T> String getXmlBodyForRequest(Class<T> declaredType, T model) {
    StringWriter sw = new StringWriter();

    JAXBContext jaxbContext = JAXBContext.newInstance(declaredType);
    Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
    jaxbMarshaller.setProperty(JAXB_FORMATTED_OUTPUT, TRUE);

    QName qName = new QName("com.companyname.testdata", "demo");
    JAXBElement<T> root = new JAXBElement<>(qName, declaredType, model);

    jaxbMarshaller.marshal(root, sw);
    return sw.toString();
}

這將問題進一步移到了堆棧上,但在某些時候您會遇到處理具體類型的代碼,然后您可以在其中指定 class 文字,如PatchRequest.class

暫無
暫無

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

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