本文介绍了无法确定自动增长默认值的属性类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
来自
Beans:
public class JavaBean {
private NestedBean nested;
}
public class NestedBean {
private String foo;
private List<NestedBean> list;
private Map<String, NestedBean> map;
}
Bind:
http://localhost:8080/mvc-showcase/convert/bean?nested.foo=bar&nested.list[0].foo=baz&nested.map[key].list[0].foo=bip
异常:
NullValueInNestedPathException: Invalid property 'nested.map[key]' of bean class [org.springframework.samples.mvc.convert.JavaBean]: Could not determine property type for auto-growing a default value
推荐答案
使用 LazyMap
,如下所示:
public class LazyMap<K, V> implements Map<K, V> {
private Map<K, V> nestedMap;
private Class<V> valueType;
public LazyMap(Class<V> valueType) {
nestedMap = new HashMap<K, V>();
this.valueType = valueType;
}
@Override
public void clear() {
nestedMap.clear();
}
@Override
public boolean containsKey(Object key) {
return nestedMap.containsKey(key);
}
@Override
public boolean containsValue(Object value) {
return nestedMap.containsValue(value);
}
@Override
public Set<java.util.Map.Entry<K, V>> entrySet() {
return nestedMap.entrySet();
}
@SuppressWarnings("unchecked")
@Override
public V get(Object key) {
if (!containsKey(key)) {
try {
put((K) key, valueType.newInstance());
} catch (Exception e) {
throw new IllegalArgumentException(e);
}
}
return nestedMap.get(key);
}
@Override
public boolean isEmpty() {
return nestedMap.isEmpty();
}
@Override
public Set<K> keySet() {
return nestedMap.keySet();
}
@Override
public V put(K key, V value) {
return nestedMap.put(key, value);
}
@Override
public void putAll(Map<? extends K, ? extends V> m) {
nestedMap.putAll(m);
}
@Override
public V remove(Object key) {
return nestedMap.remove(key);
}
@Override
public int size() {
return nestedMap.size();
}
@Override
public Collection<V> values() {
return nestedMap.values();
}
}
Bean:
public class NestedBean {
private String foo;
private List<NestedBean> list;
private Map<String, NestedBean> map = new LazyMap<String, NestedBean>(NestedBean.class);
}
这篇关于无法确定自动增长默认值的属性类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!