user3347819
user3347819

Reputation: 209

How to create a java class with dynamic number of variables

I want to create a java class with dynamic number of variables. Those dynamic variables will be read from a config file.

Example: I have a properties file like,

{
 "data": "int",
 "name": "string",
 "addr": "string",
 "age" : "int"
}

In some cases, new variables can be there or few variables are missing from above config.

I want to create a java with variables mentioned in above properties file. Is it possible in java to create such class and if yes then can someone provide sample code for that?

Upvotes: 0

Views: 2961

Answers (4)

rahul.taicho
rahul.taicho

Reputation: 1379

How about something like this

public class Model {
  Map model;

  public Model(String json) {
    model = new Gson().fromJson(jsonModel, Map.class);
  }

  public Object getValue(String key) {
    return model.get(key);
  }
}

But you'd rather want your model to hold data for values, leaving the type inference of the fields to Java.

Upvotes: 0

mstorkson
mstorkson

Reputation: 1260

I think you need to do a bit more research on java classes. There is no java class that has a dynamic "number" of variables. But you can give a class attributes, but require only some are set, for example.

class DataFile {

    int data;
    String name;
    String addr;
    int age;
}

And then you can create setters and getters for each field.

public void setName(String name) {
    this.name = name;
}

public String getName() {
    return this.name;
}

That way you can instantiate a member of the class and set the data you have.

DataFile d = new DataFile();
d.setName("John");

Remember that any class methods like setName and getName have to be inside the { } that define the class to which they belong. They aren't here just to separate them visually.

Upvotes: 1

GhostCat
GhostCat

Reputation: 140417

All of that already exists. It is called "Properties" in Java, too.

So, simply read about them here!

In other words: you could/should use java.util.Properties; and there is full support for reading that information from files; or writing to.

The Java property file format does not match your current file format; but well, when you are doing "true" Java, then the most "off the shelf" solution are Java properties; so so you could consider to change your file format.

And to give the actual answer: Java does not support a dynamic number of fields. That is what Maps are used for; and the Property class is exactly that - some sort of Map with additional functionality.

Upvotes: 0

Define a Map<String, String> that you can access by the key,

but why?

at the end all those "variables" will be the same type... -> String...

the same principe is done in config or property files....

Upvotes: 1

Related Questions