Java 为单个jaxb实例传递两个不同的类
下面是我创建jaxb实例的单例类。 我正在使用Java 为单个jaxb实例传递两个不同的类,java,jaxb,singleton,marshalling,unmarshalling,Java,Jaxb,Singleton,Marshalling,Unmarshalling,下面是我创建jaxb实例的单例类。 我正在使用contextObject进行编组和解编组。但在这两种情况下,我有不同的.class(class abc)。问题是contextObj只会为一个类创建一次,比如说编组。但我正在使用另一个.class进行解组。那么在这个代码中我怎么做呢?谢谢 public class JAXBInitialisedSingleton { private static JAXBContext contextObj = null; private JA
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;
}
}
您已经注意到单个对象
JAXBContext contextObj
这还不够
相反,您需要从Class
对象映射到JAXBContext
对象
您需要稍微重新组织一下getInstance(类)
方法。
只有3行(标有/!!
)需要更改。
在Map
中,保留迄今为止创建的所有JAXBContext
对象。
无论何时,只要您需要先前创建的JAXBContext
,
您可以在地图中找到它,并可以重用它
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;
}
}
公共类jaxbinInitialisedSingleton{
私有静态映射contextMap=新HashMap();/!!
私有jaxBinInitialisedSingleton(){
}
公共静态JAXBContext getInstance(类abc){
JAXBContext contextObj=contextMap.get(abc);/!!
试一试{
if(contextObj==null){
contextObj=JAXBContext.newInstance(abc);
contextMap.put(abc,contextObj);/!!
}
}捕获(JAXBEException e){
抛出新的非法状态异常(“无法初始化”);
}
返回contextObj;
}
}
## 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);
}
}
}