BeanUtils源码解析总结 🤞这次都给他拿下🤞
正菜来了⛳⛳⛳
这个BeanUtils类的主要作用是:JavaBeans 的静态便捷方法:用于实例化 bean、检查 bean 属性类型、复制 bean 属性等。
含义:这个成员变量使用于定义一个对象,用于类中日志的生成。
通过往底层查找,最后返回的事一个Log4jLog对象。
private static final Log logger = LogFactory.getLog(BeanUtils.class);
含义:这个用于保存未知的编辑器类型。
private static final Set<Class<?>> unknownEditorTypes = Collections.newSetFromMap(new ConcurrentReferenceHashMap<>(64));
含义:这个变量的含义就是用与存储默认的类型的值,用于存储相应的类型以及对应的默认值,如:int 默认是0,byte默认的为(byte)0
private static final Map<Class<?>, Object> DEFAULT_TYPE_VALUES;
含义:这个函数的含义就是把不同的类型已经其默认的值添加到map中,并调用Collections.unmodifiableMap(values),把创建的map转化为一个不可修改的map,unmodifiableMap()这个函数会重新创建一个UnmodifiableMap类型的把values中的键值对传进去。
static {
Map<Class<?>, Object> values = new HashMap<>();
values.put(boolean.class, false);
values.put(byte.class, (byte) 0);
values.put(short.class, (short) 0);
values.put(int.class, 0);
values.put(long.class, (long) 0);
DEFAULT_TYPE_VALUES = Collections.unmodifiableMap(values);
}
含义:使用其无参数构造函数实例化类的便捷方法,函数的开头显示一个Assert.notnull 断言表示对象非空,然后再根据类型创建一个指定类的对象。
public static <T> T instantiate(Class<T> clazz) throws BeanInstantiationException {
Assert.notNull(clazz, "Class must not be null");
if (clazz.isInterface()) {
throw new BeanInstantiationException(clazz, "Specified class is an interface");
}
try {
return clazz.newInstance();
}
catch (InstantiationException ex) {
throw new BeanInstantiationException(clazz, "Is it an abstract class?", ex);
}
catch (IllegalAccessException ex) {
throw new BeanInstantiationException(clazz, "Is the constructor accessible?", ex);
}
}
使用其“主”构造函数(对于 Kotlin 类,可能声明了默认参数)或其默认构造函数(对于常规 Java 类,需要标准的无参数设置)实例化一个类,其内部调用的函数instantiateClass也是调用构造器返回一个实例。
public static <T> T instantiateClass(Class<T> clazz) throws BeanInstantiationException {
Assert.notNull(clazz, "Class must not be null");
if (clazz.isInterface()) {
throw new BeanInstantiationException(clazz, "Specified class is an interface");
}
try {
return instantiateClass(clazz.getDeclaredConstructor());
}
catch (NoSuchMethodException ex) {
Constructor<T> ctor = findPrimaryConstructor(clazz);
if (ctor != null) {
return instantiateClass(ctor);
}
throw new BeanInstantiationException(clazz, "No default constructor found", ex);
}
catch (LinkageError err) {
throw new BeanInstantiationException(clazz, "Unresolvable class definition", err);
}
}
含义:这个函数主要是通过反射的方法找到传入的clazz这个类中有多少构造函数,如无参构造函数,不同参数和个数的构造函数。
public static <T> Constructor<T> findPrimaryConstructor(Class<T> clazz) {
Assert.notNull(clazz, "Class must not be null");
if (KotlinDetector.isKotlinReflectPresent() && KotlinDetector.isKotlinType(clazz)) {
Constructor<T> kotlinPrimaryConstructor = KotlinDelegate.findPrimaryConstructor(clazz);
if (kotlinPrimaryConstructor != null) {
return kotlinPrimaryConstructor;
}
}
return null;
}
关于通过反射获取类中局部变量和方法的函数就不再多赘述,最常用的的就是 BeanUtils中的opyProperties方法,这个方法的作用就是把源对象中的向量拷贝到des对象中去。 BeanUtils.copyProperties(src,des);
以上是关于BeanUtils的简单总结,希望有所帮助,Written By 知识浅谈