0

As part of my RFT QA Automation, I have to store the state(Object) of Java bean and should access the object across the whole application, Singleton may not work here as it is not a web application, would you please suggest any other approach to store the state of java beans.

Appreciate your help.

Thanks

TP_JAVA
  • 1,002
  • 5
  • 23
  • 49
  • 3
    singleton doesn't have anything to do with web application – ACV Jan 03 '18 at 16:21
  • you can use singleton – ACV Jan 03 '18 at 16:21
  • But by the time I try to access the object it may be claimed by GC and it will create a new instance and I will loose the state.I would like to hold the same state through out the application until my test scripts completed. – TP_JAVA Jan 03 '18 at 16:35
  • GC won't touch your singleton because it references to itself. – ACV Jan 04 '18 at 11:07

2 Answers2

0

I'm not sure to understand your problem but why not:

  • serialize the objects to disk/database/...
  • use a static store (static singleton)
Mumrah81
  • 2,034
  • 2
  • 16
  • 23
  • I can create a class with static Map which has all the values, but I need a class with setters and getters like a java bean.. – TP_JAVA Jan 03 '18 at 16:56
  • 1
    You can also create:a class containing static objects or a static map containing objects then you can use getter and setter: -MyClass.myStaticObject.getX()/MyClass.MyStaticObject.setX("val") -MyClass.myStaticMap.get("objId").getX()/MyClass.myStaticMap.get("objId").setX("val") – Mumrah81 Jan 03 '18 at 22:38
  • Your object will never be GC collected while a reference to the object exists. The only exception to this rule is when you're using Weak reference (WeakHashMap,...) – Mumrah81 Jan 03 '18 at 22:47
0

Basically it is a typical Serialization/Deserialization issue. In general you need an ability to write the state of the class on to persistant layer and then to be able to restore the "same" instance from persistant layer. There is a built-in Java mechanizm that works through Serializable interface. However it is rarely used due to its inconvinience. One of te most popular ways to do this is to Serialize your class instances into JSON or XML format and then read it back and instanciate it from that format. If you need the Text to be human readable XML is preferred, otherwise JSON is the usual choice. The best tool to use for JSON serialization is JSON Jackson (FasterXML/jackson) Here are the relevant links: Json Jackson home. The main class that you will need to use is ObjectMapper. It is easy to use. Here is an article with example. Once you get a Json String of your instance write it into a file or DB and then read it and use ObjectMapper to -recreate your instance. It is simple and works very well

Michael Gantman
  • 7,315
  • 2
  • 19
  • 36