简体   繁体   中英

Object to generic type casting

I am using a JaxB2Marshaller and want to cast the unmarshalled Object to a genric type

JAXBElement<?> myPayload = (JAXBElement<?>)marshaller.unmarshal(new StreamSource(new 
ByteArrayInputStream(otherPayload)))

I want the (?) to be a type of an interface(say BaseMessageType).

Do i need to write a cast method like below or there is a easier way t do this.

public static <T> T convertInstanceOfObject(Object o, Class<T> clazz) {
            try {
                return clazz.cast(o);
            } catch (ClassCastException e) {
                return null;
            }
        }

This could be something like following:

public static <T extends BaseMessageType> T convertInstanceOfObject(Object o, Class<T> clazz) {
            try {
                return clazz.cast(o);
            } catch (ClassCastException e) {
                return null;
            }
        }

<T> to <T extends BaseMessageType>

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM