我正在寻找一种方法来将实例化的对象及其所有属性存储到外部位置并在以后重用它。
到目前为止我尝试过:
我遇到了这个[序列化?]答案并尝试了它,但我得到的对象是空的。
算法/粗略代码:
@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();
}
}
}
一些信息:
这实际上与这个SO问题中的Selenium WebDriver问题有关。
所以我要做的是:
我没有序列化的先验背景,我不确定我正在尝试做的事情是否可行。任何帮助或指导都非常感谢。
假设 Driver 类也实现了 Serializable,我在您的代码中看到的一个问题是驱动程序被声明为受保护的静态驱动程序驱动程序,但假设创建此类实例的方法 1 永远不会被执行,因此您在序列化它时没有该对象。 在像这样序列化方法 1 之前尝试调用方法 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();
}
}
<</div>
div class="one_answers"> 虽然仍然不完整,但我至少设法使用 JAXB-MOXy 存储对象。我决定使用此解决方案来解决我的问题,因为我在使用 ObjectOutputStream 时遇到问题,主要是因为我尝试导出的类上使用的对象是第三方并且没有实现可序列化。
对于那些将面临类似问题的人,您可能会发现以下链接很有帮助: