Using Generics to return Dynamic JAXBElement

匿名 (未验证) 提交于 2019-12-03 08:56:10

问题:

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.

回答1:

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


回答2:

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

or possibly make T obj's type

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


回答3:

Another option of a JAXBElement generic

public class Example<T> {      public JAXBElement<T> toDo(final T genericType, Class<T> operationClass) {         final JAXBElement<T> jaxbElement =              new JAXBElement<T>(new QName(operationClass.getClass().getSimpleName()), operationClass, genericType);          return jaxbElement;     }         } 

Regards!



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!