I have some properties from db which need to add all those properties to a class dynamically with setters and getters
public class SearchClass{
dynamic properties
//
getters
setters
}
I have some properties from db which need to add all those properties to a class dynamically with setters and getters
public class SearchClass{
dynamic properties
//
getters
setters
}
A Map
will do this. Your choices for key are as follows:
Integer
- can be declared using public static final int PROPERTY_NAME = 0;
(increment as needed)String
- similar to Integer
enum
- This can conveniently be iterated over if you need to apply an operation to the entire set of properties.To access from outside your class, simply make a getter and setter for your map, and use searchClass.getMap().get(key);
to retrieve the properties.
For your values, if you know their type in advance (e.g. if they will all be String
s, you can define your Map
as Map<SearchKey, String> (
SearchKeybeing an example enum name).
If however your map contains many types it must be defined as
Map`, and you must manually cast values to the desired type.
If you only use a few types of value, it may be worth having multiple maps, with one for each type, e.g.:
private Map<SearchKey, Integer> ints = ...
private Map<SearchKey, String> strings = ...
private Map<SearchKey, Boolean> booleans = ...
and so on.