Reputation: 149
I have a list of variables names (which I will fetch from Database) as:
List<String> variableNames= ["name", "age", "gender"];
and these variable names will be dynamic based on table data in database.
Now, I want to be able to create a dynamic class out of these variables, like:
public class PersonDTO{
private String name;
private String age;
private String gender;
//getter and setters
}
Is there anyway, I can do this in java?
Upvotes: 1
Views: 633
Reputation: 18480
You can use Map<String, Object>
where DB column is key and the column data is the value of map.
Map<String, Object> PersonDTO = new Hashmap<>();
map.put("age", new Integer());
map.put("name", new String());
String name = (String)map.get("name");
Upvotes: 0
Reputation: 420
Java does not have a way of creating dynamic variables.
You need to declare variable in your code itself.
You could instead use a map in some way to achieve your goals.
Map<String,String> map = new HashMap<String,String>();
map.put("name","value");
...
Upvotes: 1