我有以下要概括的JAXB解组代码。看起来是这样的:

private Object getResponseObject(String stubbedXmlFile,
        Class jaxbInterfaceClass,
        AbstractRepository repository) {
    Object responseObject = null;
    try {
        JAXBContext jc = JAXBContext.newInstance(jaxbInterfaceClass);
        Unmarshaller u = jc.createUnmarshaller();
        InputStream resourceAsStream = TestProvidePensionValuationRepository.class.getClassLoader()
                .getResourceAsStream(stubbedXmlFile);
        BufferedReader br = new BufferedReader(new InputStreamReader(resourceAsStream));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }
        br.close();
        ByteArrayInputStream byteStream =
               new ByteArrayInputStream(sb.toString().getBytes());
        responseObject = u.unmarshal(byteStream);
    } catch (JAXBException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return responseObject;
}


我的目标不是返回Object,而是返回作为参数传入的同一类(例如jaxbInterfaceClass)。我在想使用泛型可能会实现这一点,但作为通用的相对新手,我感到很困惑。任何帮助表示赞赏!

最佳答案

这根本不是一个JAXB问题,只是对所需的泛型进行了一些调整:

private <T> T getResponseObject(String stubbedXmlFile,
                                Class<T> jaxbInterfaceClass,
                                AbstractRepository repository) {
    T responseObject = null;
    // code as before
    responseObject = (T) u.unmarshal(byteStream);

    return responseObject;
}


这可能会引发编译器警告,但这在将泛型代码与非泛型代码(例如JAXB)桥接的代码中并不少见。

然后,您可以使用以下命令进行调用:

MyType x = getResponseObject(file, MyType.class, repo);

关于java - 泛型可以避免我回传一个泛型的“对象”吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3924719/

10-15 03:34