gpt4 book ai didi

java - 无法确定自动增长默认值的属性类型

转载 作者:行者123 更新时间:2023-11-30 09:36:10 37 4
gpt4 key购买 nike

来自 Spring Projects Issue Tracker

bean 类:

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

异常(exception):

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

}

关于java - 无法确定自动增长默认值的属性类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10944867/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com