【问题标题】:Passing two different classes for single jaxb instance为单个 jaxb 实例传递两个不同的类
【发布时间】:2018-04-26 22:52:44
【问题描述】:
下面是我创建 jaxb 实例的单例类。
我正在使用contextObject 进行编组和解组。但在这两种情况下,我都有不同的 .class(我的代码中的 Class abc)。问题是contextObj 只会为一个类创建一次,比如说编组。但我正在使用另一个 .class 进行解组。那我怎么能在这段代码中做到这一点?谢谢
public class JAXBInitialisedSingleton {
private static JAXBContext contextObj = null;
private JAXBInitialisedSingleton() {
}
public static JAXBContext getInstance(Class abc) {
try {
if (contextObj == null) {
contextObj = JAXBContext.newInstance(abc);
}
} catch (JAXBException e) {
throw new IllegalStateException("Unable to initialise");
}
return contextObj;
}
}
【问题讨论】:
标签:
java
jaxb
singleton
marshalling
unmarshalling
【解决方案1】:
你已经注意到单个对象JAXBContext contextObj
还不够。
相反,您需要一个从Class 对象到JAXBContext 对象的Map<Class, JAXBContext> 映射。
您需要稍微重新组织您的 getInstance(Class) 方法。
只需更改 3 行(标有//!!)。
在Map 中,您保留了迄今为止创建的所有JAXBContext 对象。
每当您需要之前已经创建的 JAXBContext 时,
您可以在Map 中找到它并可以重复使用它。
public class JAXBInitialisedSingleton {
private static Map<Class, JAXBContext> contextMap = new HashMap<>(); //!!
private JAXBInitialisedSingleton() {
}
public static JAXBContext getInstance(Class abc) {
JAXBContext contextObj = contextMap.get(abc); //!!
try {
if (contextObj == null) {
contextObj = JAXBContext.newInstance(abc);
contextMap.put(abc, contextObj); //!!
}
} catch (JAXBException e) {
throw new IllegalStateException("Unable to initialise");
}
return contextObj;
}
}
【解决方案2】:
## You can try like below -##
public final class JAXBContextConfig
{
private JAXBContextConfig()
{
}
public static final JAXBContext JAXB_CONTEXT_REQ;
public static final JAXBContext JAXB_CONTEXT_RES;
static
{
try
{
JAXB_CONTEXT_REQ = JAXBContext.newInstance(Request.class);
JAXB_CONTEXT_RES = JAXBContext.newInstance(Response.class);
}
catch (JAXBException e)
{
throw new ManhRestRuntimeException(e);
}
}
}