我正在尝试使用Stanford CoreNLP库,并希望序列化主要的StanfordCoreNLP管道对象,但它会抛出java.io.NotSerializableException异常。
完整的故事: 每次我运行我的实现时,需要约15秒钟将管道注释器和分类器加载到内存中。最终进程在内存中约为600MB(足够小,可以存储在我的情况下)。我想在第一次创建后保存此管道,以便以后只需将其读入内存即可。
然而,它会抛出NotSerializableException异常。我尝试制作一个微不足道的子类来实现Serializable接口,但StanfordCoreNLP具有未实现此接口的注释器和分类器属性,我无法为所有这些属性制作子类。
是否有任何Java库可以序列化未实现Serializable接口的对象?我想它必须递归遍历其属性并对任何类似的对象执行相同操作。
我尝试过的序列化代码:
完整的故事: 每次我运行我的实现时,需要约15秒钟将管道注释器和分类器加载到内存中。最终进程在内存中约为600MB(足够小,可以存储在我的情况下)。我想在第一次创建后保存此管道,以便以后只需将其读入内存即可。
然而,它会抛出NotSerializableException异常。我尝试制作一个微不足道的子类来实现Serializable接口,但StanfordCoreNLP具有未实现此接口的注释器和分类器属性,我无法为所有这些属性制作子类。
是否有任何Java库可以序列化未实现Serializable接口的对象?我想它必须递归遍历其属性并对任何类似的对象执行相同操作。
我尝试过的序列化代码:
static StanfordCoreNLP pipeline;
static String file = "/Users/ME/Desktop/pipeline.sav";
static StanfordCoreNLP pipeline() {
if (pipeline == null) {
try {
FileInputStream saveFile = new FileInputStream(file);
ObjectInputStream read = new ObjectInputStream(saveFile);
pipeline = (StanfordCoreNLP) read.readObject();
System.out.println("Pipeline loaded from file.");
read.close();
} catch (FileNotFoundException e) {
System.out.println("Cached pipeline not found. Creating new pipeline...");
Properties props = new Properties();
props.put("annotators", "tokenize, ssplit, pos, lemma, ner, parse, dcoref");
pipeline = new StanfordCoreNLP(props);
savePipeline(pipeline);
} catch (IOException e) {
System.err.println(e.getLocalizedMessage());
} catch (Exception e) {
System.err.println(e.getLocalizedMessage());
}
}
return pipeline;
}
static void savePipeline(StanfordCoreNLP pipeline) {
try {
FileOutputStream saveFile = new FileOutputStream(file);
ObjectOutputStream save = new ObjectOutputStream(saveFile);
save.writeObject(pipeline);
System.out.println("Pipeline saved to file.");
save.close();
} catch (FileNotFoundException e) {
System.out.println("Pipeline file not found during save.");
} catch (IOException e) {
System.err.println(e.getLocalizedMessage());
}
}