我正在寻找一种方法将实例化对象及其所有属性存储到外部位置,以后再重复使用。
到目前为止我尝试了什么:
我遇到了这个[Serialization?]的答案并试了一下,但我得到的对象是空的。
Algo / Rough代码:
@Listeners(TestListener.class)
public class TestRunner {
protected static Driver driver; //Driver implements WebDriver interface
//Step 1
public void method1(){
driver = new Driver(1); //creates a customized chromedriver instance. Chrome driver / browser session is opened here.
}
//Step 2
public void method2(){
try {
FileOutputStream fileOut = new FileOutputStream("card.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(driver);
out.close();
fileOut.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
//Step 3
//Just manually stop the test/debugger for testing
//Step 4
public void method4(){
try {
FileInputStream fileIn = new FileInputStream("card.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
driver = (Driver) in.readObject(); //here driver returns as null. In this line, im hoping to recreate the previous object to somehow control the browser again
in.close();
fileIn.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
有些信息:
这实际上与this SO问题中的Selenium WebDriver问题有关。
所以我想做的是:
我没有序列化的先前背景,我不确定我尝试做的事情是否可行。非常感谢任何帮助或指导。
答案 0 :(得分:1)
假设Driver类也实现了Serializable,我在你的代码中看到的一个问题是驱动程序被声明为受保护的静态驱动程序驱动程序,但是假设创建此类实例的方法1永远不会被执行,所以你不要# 39;当你序列化时,它有这个对象。尝试在序列化之前调用方法1:
public void method2(){
try {
FileOutputStream fileOut = new FileOutputStream("card.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
method1();
out.writeObject(driver);
out.close();
fileOut.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
答案 1 :(得分:0)
虽然仍然不完整,但我设法至少使用JAXB-MOXy存储对象。 我已经决定使用这个解决方案解决我的问题因为我在使用ObjectOutputStream时遇到麻烦主要是因为我试图导出的类上使用的对象是第三方而且没有实现Serializable。
对于那些将面临类似问题的人,您可能会发现以下链接很有用: