Spring的BeanUtils.getPropertyDescriptors 学习



/**
* 类中的某些字段不校验 并返回空字段名
*/
public static List<String> validateProperty(Object validateObj, String... ignoreProperties) {
PropertyDescriptor[] targetPds = BeanUtils.getPropertyDescriptors(validateObj.getClass());
List<String> ignoreList = (ignoreProperties != null ? Arrays.asList(ignoreProperties) : null);
List<String> errList = new ArrayList<>();
for (PropertyDescriptor targetPd : targetPds) {
Method readMethod = targetPd.getReadMethod();
if (readMethod != null && (ignoreList == null || !ignoreList.contains(targetPd.getName()))) {
try {
if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
readMethod.setAccessible(true);
}
Object value = readMethod.invoke(validateObj);
if (value instanceof String) {
if (StrUtil.isEmpty((String) value)) {
errList.add(validateObj.getClass().getSimpleName() + "中的" + targetPd.getName() + "不能为空");
continue;
}
}
if (value == null) {
errList.add(validateObj.getClass().getSimpleName() + "中的" + targetPd.getName() + "不能为空");
}

if (!targetPd.getName().equals("class"))
map.put(targetPd.getName(), value);

} catch (Throwable ex) {
throw new FatalBeanException(
"Could not copy property '" + targetPd.getName() + "' from source to target", ex);
}
}
}

map.forEach((k, v) -> {
System.out.println(k + ":" + v);
});
return errList;

}
---------------------------------------------------------
偶得如上代码 用以拿到一个类中的所有字段名和对应的值
直接看代码 找到了
static CachedIntrospectionResults forClass(Class<?> beanClass) throws BeansException {
CachedIntrospectionResults results = strongClassCache.get(beanClass);
if (results != null) {
return results;
}
results = softClassCache.get(beanClass);
if (results != null) {
return results;
}

results = new CachedIntrospectionResults(beanClass);
ConcurrentMap<Class<?>, CachedIntrospectionResults> classCacheToUse;

if (ClassUtils.isCacheSafe(beanClass, CachedIntrospectionResults.class.getClassLoader()) ||
isClassLoaderAccepted(beanClass.getClassLoader())) {
classCacheToUse = strongClassCache;
}
else {
if (logger.isDebugEnabled()) {
logger.debug("Not strongly caching class [" + beanClass.getName() + "] because it is not cache-safe");
}
classCacheToUse = softClassCache;
}

  // 在这一行之后 强引用Map添加了缓存
   CachedIntrospectionResults existing = classCacheToUse.putIfAbsent(beanClass, results);
return (existing != null ? existing : results);
}
-------------------
因此 当对象第一次来的时候 反射创建 后续走到之后 就会走缓存了











免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM