Java:如何将整个对象存储到外部位置并重用它来重新创建对象以供以后使用?

时间:2017-05-16 02:57:37

标签: java serialization selenium-webdriver webdriver

我正在寻找一种方法将实例化对象及其所有属性存储到外部位置,以后再重复使用。

到目前为止我尝试了什么:
我遇到了这个[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问题有关。

所以我想做的是:

  • 第1步:创建Chrome驱动程序的自定义实例
  • 步骤2:使用上面的代码将创建的对象存储到外部源中
  • 第3步:我故意停止测试以模拟失败
  • 第4步:我尝试通过读取存储的源重新创建上一个对象。

    我没有序列化的先前背景,我不确定我尝试做的事情是否可行。非常感谢任何帮助或指导。

  • 2 个答案:

    答案 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。

    对于那些将面临类似问题的人,您可能会发现以下链接很有用:

  • Make your JAXB cleaner with the MOXy implementation
  • Handling interfaces in JAXB with MOXy