下面是我创建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;
}
}
发布于 2018-04-27 14:53:07
您已经注意到,单对象JAXBContext contextObj
是不够的。
相反,您需要一个从Class
对象到JAXBContext
对象的Map
映射。
您需要稍微重新组织一下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;
}
}
发布于 2018-09-25 11:12:11
## 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);
}
}
}
https://stackoverflow.com/questions/50052956
复制相似问题