2

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

4 Answers 4

3

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

1 Comment

The first suggestion of using a raw type worked for my purposes, but I'll go back and give this a shot to see the "proper" way of doing it. Thanks for the info!
1

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

Comments

0

If you don't care what type JAXBElement is of (i.e. you don't care if it's a JAXBElement<String> or JAXBElement<Foo>, then you can simply use the raw type (JAXBElement) and leave off the type parameter. This will generate a warning which you can suppress.

1 Comment

Wow, I can't believe I missed that. Thanks!
0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.