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;
}

1 Answer 1

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 {
Sign up to request clarification or add additional context in comments.

1 Comment

I think you just mean clazz.cast(temp); since clazz.getClass() will return Class.class.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.