使用泛型返回动态JAXBElement [英] Using Generics to return Dynamic JAXBElement

查看:380
本文介绍了使用泛型返回动态JAXBElement的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有多个根元素,因此我需要编写

I have multiple root elements and thus, I need to write

JAXBElement<BookType> jaxbBookType = objectFactory.createBookType (bookType);
JAXBElement<OrderType> jaxbOrderType = objectFactory.createOrderType (orderType);

等等。我不想一次又一次地写这段代码。我正在尝试编写一个方法,它将根据其输入返回我JAXBElement。

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.

推荐答案

如果您可以假设使用 instanceof 运算符参数,只需转换为 JAXBElement< T> 即可:

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

请注意,您还必须传递 T Class (code> T.getName()):
$ b $>这样它就可以在运行时使用了b

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

这篇关于使用泛型返回动态JAXBElement的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆