How to create bean/s(retaining column datatype in bean) dynamically after reading columns from table/s in java ?
解决方案
UPDATE
Previous answer was an attempt to solve the issue immediately.
So it's not the final code for FlexBean.
For the final code, visit https://github.com/ramazanpolat/flexbean
OLD ANSWER
I had the same problem so I wrote FlexBean.
public class FlexBean {
private List propertyNames = new ArrayList<>();
private Map propertyValueMap = new LinkedHashMap<>();
private List propertyTypes = new ArrayList<>();
public FlexBean() {
}
public void setProperties(Map props){
for (String propName:props.keySet()){
addProperty(propName, props.get(propName));
}
}
public void addPropertyNames(List propertyNames){
for (String name: propertyNames) {
addProperty(name);
}
}
public Collection getPropertyValues(){
return propertyValueMap.values();
}
public List getPropertyNames() {
return propertyNames;
}
public Map getPropertyValueMap() {
return propertyValueMap;
}
public List getPropertyTypes() {
return propertyTypes;
}
public void addProperty(String propName, Type propType){
propertyNames.add(propName);
propertyTypes.add(propType);
}
public void addProperty(String propName){
// default property type is String
addProperty(propName, String.class);
}
public void addProperty(String propName, Object value){
addProperty(propName);
setProperty(propName, value);
}
public void addProperty(String propName, Type propType, Object value){
addProperty(propName, propType);
setProperty(propName, value);
}
public int getPropertyIndex(String propName){
return propertyNames.indexOf(propName);
}
public Type getPropertyType(String propName){
int index = getPropertyIndex(propName);
return Iterables.get(propertyTypes,index);
}
public void setProperty(String propName, Object propValue){
propertyValueMap.put(propName, propValue);
}
public Object getPropertyValue(String propName){
return propertyValueMap.get(propName);
}
public Any getTypedPropertyValue(String propName){
return (Any)((Any) propertyValueMap.get(propName));
}
public Object getProperty(int propIndex){
return Iterables.get(propertyValueMap.entrySet(),propIndex).getValue();
}
}
Usage:
FlexBean flexBean = new FlexBean();
flexBean.addProperty("prop1", 1); // int inferred
flexBean.addProperty("prop2", "value2"); // string inferred
flexBean.addProperty("prop3", 0.1f); // float inferred
for (Object o: flexBean.getPropertyValues()) {
System.out.println(o);
}
int prop1 = flexBean.getTypedPropertyValue("prop1");
String prop2 = flexBean.getTypedPropertyValue("prop2");
float prop3 = flexBean.getTypedPropertyValue("prop3");