This commit is contained in:
Looly
2024-08-27 16:03:02 +08:00
parent 55b433c4ca
commit 12a3679c20
7 changed files with 63 additions and 6 deletions

View File

@@ -133,7 +133,9 @@ public class DynaBean implements Cloneable, Serializable {
} else {
final PropDesc prop = BeanUtil.getBeanDesc(beanClass).getProp(fieldName);
if (null == prop) {
throw new BeanException("No public field or get method for {}", fieldName);
// 节点字段不存在类似于Map无key返回null而非报错
return null;
//throw new BeanException("No public field or get method for {}", fieldName);
}
return (T) prop.getValue(bean);
}

View File

@@ -18,6 +18,8 @@ package org.dromara.hutool.core.bean.path.node;
import org.dromara.hutool.core.bean.DynaBean;
import org.dromara.hutool.core.math.NumberUtil;
import org.dromara.hutool.core.reflect.ClassUtil;
import org.dromara.hutool.core.text.StrUtil;
/**
* 处理名称节点或序号节点,如:
@@ -58,7 +60,12 @@ public class NameNode implements Node {
if ("$".equals(name)) {
return bean;
}
return DynaBean.of(bean).get(this.name);
Object value = DynaBean.of(bean).get(this.name);
if(null == value && StrUtil.lowerFirst(ClassUtil.getClassName(bean, true)).equals(this.name)){
// 如果bean类名与属性名相同则返回bean本身
value = bean;
}
return value;
}
@Override

View File

@@ -22,7 +22,6 @@ import org.dromara.hutool.core.collection.CollUtil;
import org.dromara.hutool.core.collection.ListUtil;
import org.dromara.hutool.core.exception.HutoolException;
import org.dromara.hutool.core.lang.Assert;
import org.dromara.hutool.core.map.MapUtil;
import org.dromara.hutool.core.math.NumberUtil;
import org.dromara.hutool.core.text.StrPool;
import org.dromara.hutool.core.text.placeholder.StrTemplate;
@@ -354,7 +353,7 @@ public class NamedPlaceholderStrTemplate extends StrTemplate {
* @return 格式化字符串
*/
public String format(final Map<String, ?> map) {
if (MapUtil.isEmpty(map)) {
if (null == map) {
return getTemplate();
}
return format(map::get, map::containsKey);

View File

@@ -334,6 +334,21 @@ public class BeanUtilTest {
assertEquals("sub名字", subName);
}
@Test
public void getPropertyWithClassNameTest() {
final SubPerson person = new SubPerson();
person.setAge(14);
person.setOpenid("11213232");
person.setName("测试A11");
person.setSubName("sub名字");
// 获取Bean属性时如果用户传入名称以对象名开头则自动去掉对象名获取剩余部分的属性值
final Object name = BeanUtil.getProperty(person, "subPerson.name");
assertEquals("测试A11", name);
final Object subName = BeanUtil.getProperty(person, "subPerson.subName");
assertEquals("sub名字", subName);
}
@Test
@SuppressWarnings("ConstantConditions")
public void getNullPropertyTest() {

View File

@@ -43,6 +43,9 @@ public class DynaBeanTest {
//执行指定方法
final Object invoke = bean2.invoke("testMethod");
Assertions.assertEquals("test for 李华", invoke);
// 不存在的字段测试
Assertions.assertNull(bean.get("notExist"));
}