Is there a way to build a JavaBean dynamically based on the DB table column names and assoicated data? For example, if I get back of 5 columns in a db table, I need to create a javaBean with those 5 column names as variables and their getters/setters as well. Next time, if I get 7 columns, I can create a javaBean with 7 variables.
5 Answers
I think that you can do this with byte code manipulation.
2 main libraries are:
- javassist - http://www.csg.ci.i.u-tokyo.ac.jp/~chiba/javassist/
- asm - http://asm.ow2.org/
1 Comment
I don't believe you can have an object with variable fields, but you could use a Map to store the results. That might be the closest to what you want.
2 Comments
The Answer is no. You cannot ask for variables at run time. What you can do is.
Map<String, Map> results = new HashMap<String, Map>();
// Associate each column with a new map and put it in results.
// Take each variable from column and associate it with the corresponding column's hashmap.
Comments
You can implement the org.apache.commons.beanutils.DynaBean interface:
A
DynaBeanis a Java object that supports properties whose names and data types, as well as values, may be dynamically modified. To the maximum degree feasible, other components of the BeanUtils package will recognize such beans and treat them as standard JavaBeans for the purpose of retrieving and setting property values.