0

I read the posts: - Very simple Java Dynamic Casting - java: how can i do dynamic casting of a variable from one type to another?

But it did not answer exactly what I was looking for. I need to create a method that creates a class from a XML inside a String. The XSD is created and I use JAXB with success to marshall/unmarshall the XML to Class and back. But this is too static. The code below is the actual code.


    public static SaiRenovacao createClassFromString(String string,
            Class Response) throws JAXBException {
        SaiRenovacao _return = null;

    StringReader reader = new StringReader(string);
    JAXBContext jaxbContext = JAXBContext.newInstance(Response);
    Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
    Object temp = unmarshaller.unmarshal(reader);
    _return = (SaiRenovacao) temp;
    return _return;
}

I wanna change this method. I need/would like to pass a Class by parameter 'Response' and my code must instantiate this Class [JAXBContext.newInstance(Response);] and unmarshall it and return the unmarshalled class - that is the class passed as parameter in Response - to the caller.

The way it is written I can only work with SaiRenovacao class.

If I change the implementation to I will get an obvious Exception because I can not resolve Response to a type. But this is the basic idea of what I need to do.


    public static SaiRenovacao createClassFromString(String retorno,
            Class Response) throws JAXBException {
        SaiRenovacao _retorno = null;

    StringReader reader = new StringReader(retorno);
    JAXBContext jaxbContext = JAXBContext.newInstance(Response);
    Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
    Object temp = unmarshaller.unmarshal(reader);
    _retorno = (Response) temp;
    return _retorno;
}

Community
  • 1
  • 1

1 Answers1

1

Try something like

return clazz.cast(temp);

And change your method signature to

public static <T> T createClassFromString(String retorno, Class<T> clazz) throws JAXBException {
Smutje
  • 17,733
  • 4
  • 24
  • 41