首页 > 解决方案 > 生成java方法

问题描述

我有如下方法

public InstitutionsType toInstitutionPOJO(String xml) throws Exception {
        InputStream stream = new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8));
        JAXBContext jaxbContext = JAXBContext.newInstance(InstitutionsType.class);
        Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
        XMLInputFactory factory = XMLInputFactory.newInstance();
        XMLEventReader someSource = factory.createXMLEventReader(stream);
        JAXBElement<InstitutionsType> userElement = jaxbUnmarshaller.unmarshal(someSource, InstitutionsType.class);
        return userElement.getValue();
    }

public ErrorType toErrorPOJO(String xml) throws Exception {
    InputStream stream = new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8));
    JAXBContext jaxbContext = JAXBContext.newInstance(ErrorType.class);
    Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
    XMLInputFactory factory = XMLInputFactory.newInstance();
    XMLEventReader someSource = factory.createXMLEventReader(stream);
    JAXBElement<ErrorType> userElement = jaxbUnmarshaller.unmarshal(someSource, ErrorType.class);
    return userElement.getValue();
}

我必须创建大约 14 种类似的方法,除了输出类型之外它们完全相同。我们可以把这个泛化吗?

标签: java

解决方案


像这样的东西应该可以解决问题..

public <T> T  toPOJO(String xml, Class<T> type) throws Exception {
        InputStream stream = new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8));
        JAXBContext jaxbContext = JAXBContext.newInstance(type);
        Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
        XMLInputFactory factory = XMLInputFactory.newInstance();
        XMLEventReader someSource = factory.createXMLEventReader(stream);
        JAXBElement<T> userElement = jaxbUnmarshaller.unmarshal(someSource, type);
        return userElement.getValue();
}

推荐阅读