javagenericsjaxb

Using Generics to return Dynamic JAXBElement


I have multiple root elements and thus, I need to write

JAXBElement<BookType> jaxbBookType = objectFactory.createBookType (bookType);
JAXBElement<OrderType> jaxbOrderType = objectFactory.createOrderType (orderType);

and so on. I don't want to write this piece of code again and again. I am trying to write a method which will return me JAXBElement based on its input.

What i am trying to write is

public <T> JAXBElement<T> getJaxbElement (Object obj){
    if (obj instanceof OrderType){
        return objectFactory.createOrderType((OrderType)obj);
    }
}

But obviously, I am doing it wrong. Since i don't know much about Generics and after reading it for a while, I am still confuse. Can someone help me little bit here.


Solution

  • In case you can assume to use the instanceof operator with the parameter, just casting to JAXBElement<T> would be enough:

    public <T> JAXBElement<T> getJaxbElement (Object obj){
        Object ret;
        if (obj instanceof OrderType){
            ret = objectFactory.createOrderType((OrderType)obj);
        }
        else if (obj instanceof BookType){
            ret = objectFactory.createBookType((BookType)obj);
        }
        return (JAXBElement<T>) ret;
    }
    

    In case you can't, being the method name what does have to be dynamic here, a possibility is to use reflection (always unreliable and likely to backfire with all kinds of problems).

    Notice you'll also have to pass along the Class of T so that it'll be available at runtime (it's not possible to do T.getName()):

    public <T> JAXBElement<T> getJaxbElement (Object obj, Class<T> clazz){
        ObjectFactory objectFactory = getObjectFactory();
        String methodName = "create" +  clazz.getName();
        Method m = objectFactory.getClass().getDeclaredMethod(methodName, clazz);
        Object ret = m.invoke(objectFactory, obj);
        return (JAXBElement<T>) ret;
    }