Skip to content
Advertisement

Create DataObject to hold different types of data as needed

So i recently went from Javascript to Java codebase for an automation framework, when it comes to data supplied to our page object methods we usually used an object in javascript shown as this:

JavaScript

I want create the same effect in Java and my solution was creating a DataObject class that used HashMaps for the various different value Types a “DataObject” could hold. Example:

JavaScript

My problem with this approach is that sometimes my “DataObject” maybe only need to hold Strings, or Strings and Integers. With the approach i made, i am taking up unused resources to instantiate other types that wont be added to the DataObject. So i thought the better approach would be the following:

JavaScript

This way i can have methods that will ensure type safety and use HashMaps within this objectMap to store the data according to the correct type, and this allows for the HashMaps to be dynamically generated when the DataObject add methods are called, and the DataObject in the automation scripts will hold only the types it needs to store. The problem I’m encountering is that the objectMap cannot support the stringValues map because stringValues is of type: <String, String>.

Anyway i can get the objectMap to store the stringValues Map?

Advertisement

Answer

Instead of using Hashmap, use java generic types:

here is a snippet for this scenario:

JavaScript

Main class

JavaScript

Output :

DataObject{dataList=[GenericClass{key=’name’, value=sub1}, DataTypeContainer{key=’cost’, value=3}, GenericClass{key=’active’, value=true}]}

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement