mafioso mafioso - 1 year ago 73
Java Question

Create object of given data dynamically in java

I have an

in java. I read data from a
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

Or should I create an ArrayList of ArrayList?

Thanks in advance!

Answer Source

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){

   public add(String key, Object 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");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download