泛型可以避免让我传回一个通用的“对象”吗?

时间:2010-10-13 14:23:54

标签: java generics

我有以下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)。我认为这可能与Generics有关,但作为仿制药的相对新手,我很难过。任何帮助表示赞赏!

2 个答案:

答案 0 :(得分:7)

这根本不是一个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);

答案 1 :(得分:0)

您可以使用以下方法使@ skaffman的代码类型安全:

responseObject = jaxbInterfaceClass.cast(u.unmarshal(byteStream));
但是,请注意,您应该处理JAXBElement ...