Dave Novelli
Dave Novelli

Reputation: 2184

Java Reflection - Getting a Type from an object to instantiate a generic

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

Upvotes: 2

Views: 3537

Answers (4)

m.nguyencntt
m.nguyencntt

Reputation: 943

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

Upvotes: 1

Alex G
Alex G

Reputation: 1

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

Upvotes: 0

Tom Anderson
Tom Anderson

Reputation: 47173

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

Upvotes: 3

matt b
matt b

Reputation: 139921

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.

Upvotes: 0

Related Questions