I've never really used reflection before and am attempting something I'm not sure is possible. Basically, I'm trying to write a method that takes an Object
as a parameter, and then attempts to marshal that object regardless of its type. I can't figure out how to get the type to use when instantiating the generic JAXBElement<T>
object. Is this possible? My attempt:
String marshalObject(Object obj) {
Class c = obj.getClass();
Type t = (Type) c;
QName _QNAME = new QName("http://www.acme.com/ImportExport", c.getName());
StringWriter sw = new StringWriter();
try {
ObjectFactory of = new ObjectFactory();
JAXBElement<?> jaxElement = new JAXBElement<t>(_QNAME, c, null, obj);
JAXBContext context = JAXBContext.newInstance( c );
Marshaller m = context.createMarshaller();
m.marshal( jaxElement, sw );
} catch( JAXBException jbe ){
System.out.println("Error marshalling object: " + jbe.toString());
return null;
}
return sw.toString();
}
The official generics nerd way to do this is to stick a type parameter on the method. You declare it:
<T> String marshalObject(T obj) {
Then when you get the class:
Class<T> c = obj.getClass(); // something like that
Then finally:
JAXBElement<T> jaxElement = new JAXBElement<T>(_QNAME, c, null, obj);
I did simple way as below and it worked:
public static <T> JAXBElement<T> createJaxbElement(T object, Class<T> clazz) {
return new JAXBElement<>(new QName(clazz.getSimpleName()), clazz, object);
}
If needed, add QName:
private static <T> JAXBElement<T> makeQName(Object obj) {
Class c = obj.getClass();
QName qName = new QName("com.ukrcard.xmlMock", obj.getClass().getName());
return new JAXBElement<T>(qName, c, (T) obj);
}
如果您不关心JAXBElement
类型(即您不关心它是JAXBElement<String>
还是JAXBElement<Foo>
,那么您可以简单地使用原始类型( JAXBElement
)并JAXBElement
类型参数。这个将生成一个您可以抑制的警告。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.