在代码中我们往往会写很多的数据模型类型,然后这些数据模型中很多使用率并不高,甚至是在一个很小的细节中使用一次后再也无人问津,就放在那里吃灰。
在使用这些数据模型时,往往也显得不够灵活,当数据字段增加时,需要去为数据模型增加属性,数据字段减少时往往也不会有人去删除属性。
这时我们通常就会使用HashMap来作为通用的数据模型,然而在使用会涉及大量的类型转换,使用起来十分不便,所以我基于HashMap对其进行了一点作为数据模型的简单优化,使其在使用时能既通用灵活,在类型的处理上也更加简便。
public class CrazyModel extends HashMap<String, Object> {
private static final long serialVersionUID = 9016428745751329103L;
public CrazyModel() {
}
public CrazyModel(Map<String, Object> data) {
putAll(data);
}
public Integer fetchInt(String key) {
if (!containsKey(key)) return null;
Object value = get(key);
if (value instanceof BigInteger){
return ((BigInteger)value).intValue();
}else if (value instanceof Double){
return ((Double) value).intValue();
}else if (value instanceof String){
return Integer.parseInt(value.toString());
}else {
return (Integer)value;
}
}
public String fetchString(String key) {
if (!containsKey(key)) return null;
return (String) get(key);
}
public Double fetchDouble(String key) {
if (!containsKey(key)) return null;
Object value = get(key);
return value instanceof BigDecimal ? ((BigDecimal)value).doubleValue() : (Double)value;
}
public Float fetchFloat(String key) {
if (!containsKey(key)) return null;
Object value = get(key);
return value instanceof BigDecimal ? ((BigDecimal)value).floatValue() : (Float)value;
}
public BigDecimal fetchBigDecimal(String key) {
if (!containsKey(key)) return null;
Object value = get(key);
if (value instanceof Double || value instanceof Float) {
BigDecimal decimal = new BigDecimal(value + "");
return decimal;
}
return (BigDecimal)get(key);
}
public BigInteger fetchBigInteger(String key) {
if (!containsKey(key)) return null;
Object value = get(key);
if (value instanceof Integer) {
BigInteger integer = new BigInteger(value + "");
return integer;
}
return (BigInteger)get(key);
}
/**
* fetch anything what your wish
* @return your wish bean
*/
public <T> T fetchYourWish(String key){
return (T)get(key);
}
}