在尝试实例化ObjectFactory时,我在eclipse中遇到以下编译错误:
cannot instantiate the type objectfactory
此编译错误在以下行引发:
objectFactory = new ObjectFactory();//throws error: "Cannot instantiate the type ObjectFactory"
调用类的完整代码如下:
package maintest;
import java.io.File;
import javax.naming.spi.ObjectFactory;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
public class Main {
private static JAXBContext context;
private static ObjectFactory objectFactory;
public static void main(String[] args) {
try {setUp();} catch (Exception e) {e.printStackTrace();}
unmarshal();
}
protected static void setUp() throws Exception {
context = JAXBContext.newInstance("generated");
objectFactory = new ObjectFactory();//throws error: "Cannot instantiate the type ObjectFactory"
}
public static <PurchaseOrderType> void unmarshal(){
Unmarshaller unmarshaller;
try {
unmarshaller = context.createUnmarshaller();
final Object object = unmarshaller.unmarshal(new File("src/test/samples/po.xml"));
} catch (JAXBException e) {e.printStackTrace();}
}
}
如何解决此错误?
答案 0 :(得分:3)
我的猜测是您导入了错误的ObjectFactory。你可能想要xjc(JAXB相关)生成的那个不是来自javax.naming.spi(JNDI的服务提供者接口)的那个。
修改强>
javax.xml.bind.JAXBException:&#34;生成&#34;不包含 ObjectFactory.class或jaxb.index
确保&#34;生成&#34; package包含ObjectFactory(具有@XmlRegistry批注的那个,而不是javax.naming.spi.ObjectFactory实现)或jaxb.index文件。
您可能可以从代码中删除javax.naming.spi.ObjectFactory,除非您自己实现JNDI实现。
答案 1 :(得分:1)
尝试以下
import javax.naming.spi.ObjectFactory;
import javax.naming.Context;
import javax.naming.Name;
import java.util.Hashtable;
ObjectFactory objFactory = new ObjectFactory() {
@Override
public Object getObjectInstance(Object o, Name name, Context cntxt, Hashtable<?, ?> hshtbl) throws Exception {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
};