可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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!