I am looking for a way to have a generic class with dynamic numbers of properties.
Example: (Class User)
User user1 = new User(1,"john","115 street","male",60,150, 15.125);
User user2 = new User(2,"john2","116 street","male",60,150, 15.125,"New york");
etc..
Can this be done in Java or could you recommend me any possible alternatives (if not)?
Unfortunately, Java doesn’t support dynamic properties.
You can hack that with:
Vararg methods. Use the following signature
method(Object... objects).In that case you will have array of objects of your parameters passed to method – just process them as needed.
Map structure. I think its better solution, you have map with parameters inside your class. Where is key – name of your parameter and value its actual value.
Use method
addParameterto add new parameter to your object.Use method
getParameterto extract value that needed (e.ggetParameter("name")😉