mafioso mafioso - 19 days ago 6
Java Question

Create object of given data dynamically in java

I have an

ArrayList
in java. I read data from a
database
and want to add each row to this arraylist.

My problem is that I don't know how many arguments a row has. E.g. if I read from table person, a person has a
firstname, nickname, age
and if I read from an other table like player there is a different number arguments.

How can I dynamically create an object where I can add my data?

For example, how can I create something like this one dynamically:
Person = {"a", "b", 1}
and so I have an
ArrayList<Person>
.

Or should I create an ArrayList of ArrayList?

Thanks in advance!

Answer

You should rather use a HashMap<String, Object> where the key of the map will be the property name and the value of the Map, the value associated to the property.

Map<String, Object> myPerson = new HashMap<String, Object>();
myPerson.add("name", "doe");
myPerson.add("age", 20L)

Optionally, you could use a Wrapper class which contains the Map. In this way, you hide the implementation and you can provide custom methods to the client such as methods to get a value without explicit casting and you could provide a name to the mapped table :

Example :

public class DBObjectMapper{
   private Map<String, Object> map = new HashMap<String, Object>();
   private String tableName;

   private DBObjectMapper(String tableName){
       this.tableName=tableName;
   }

   public add(String key, Object value){
     map.put(key,value);
   }

   public <T extends Object> T get(String key) {
      return (T) map.get(key);
   }

   public String getTableName(){
      return tableName;
   }
}

Now, clients don't need to do explicit casts when retrieving a value from the mapper:

   DBObjectMapper mapper = new DBObjectMapper("person");
   mapper.add("isEnabled", Boolean.valueOf(true);
   mapper.add("name", "doe");
   String mappedTable = mapper.getTableName();
   Boolean b = mapper.get("isEnabled");
   String string = mapper.get("name");