从Java中的表读取列后,如何动态创建Bean(在Bean中保留列数据类型)?

最佳答案

更新
先前的答案是尝试立即解决问题。
因此,这不是FlexBean的最终代码。
有关最终代码,请访问https://github.com/ramazanpolat/flexbean

老答案

我遇到了同样的问题,所以我写了FlexBean。

public class FlexBean {
    private List<String> propertyNames = new ArrayList<>();
    private Map<String, Object> propertyValueMap = new LinkedHashMap<>();
    private List<Type> propertyTypes  = new ArrayList<>();

    public FlexBean() {

    }

    public void setProperties(Map<String, Object> props){
        for (String propName:props.keySet()){
            addProperty(propName, props.get(propName));
        }
    }


    public void addPropertyNames(List<String> propertyNames){
        for (String name: propertyNames) {
            addProperty(name);
        }
    }

    public Collection<Object> getPropertyValues(){
        return propertyValueMap.values();
    }

    public List<String> getPropertyNames() {
        return propertyNames;
    }

    public Map<String, Object> getPropertyValueMap() {
        return propertyValueMap;
    }

    public List<Type> 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> Any getTypedPropertyValue(String propName){
        return (Any)((Any) propertyValueMap.get(propName));
    }

    public Object getProperty(int propIndex){
        return Iterables.get(propertyValueMap.entrySet(),propIndex).getValue();
    }
}


用法:

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");

10-07 23:32