importorg.slf4j.Logger;importorg.slf4j.LoggerFactory;importsun.flower.sunflower.base.domain.Role;importsun.flower.sunflower.base.domain.User;importjava.beans.BeanInfo;importjava.beans.IntrospectionException;importjava.beans.Introspector;importjava.beans.PropertyDescriptor;importjava.lang.reflect.Method;importjava.lang.reflect.Modifier;public classSpringTest {private static final Logger LOGGER = LoggerFactory.getLogger(SpringTest.class);/*Introspector
Introspector 类为通过工具学习有关受目标 Java Bean 支持的属性、事件和方法的知识提供了一个标准方法
对于这三种信息,Introspector 将分别分析 bean 的类和超类,寻找显式或隐式信息,使用这些信息构建一个全面描述目标 bean 的 BeanInfo 对象。
如果某个类提供有关其自身的显式 BeanInfo,
则将它添加到从分析所有派生类得到的 BeanInfo 信息中,并将显式信息视为当前类及其基类的确定的信息,无需进一步深入超类链进行分析。
如果没有在某个类上发现显式 BeanInfo,
则使用低层次的反射来研究类的方法,并应用标准设计模式来标识属性存储器、事件源或公共方法。
然后深入分析类的超类,从它那里(可能在超类链的顶部)添加信息。*/
/*BeanInfo
该类实现此 BeanInfo 接口并提供有关其 bean 的方法、属性、事件等显式信息。*/
/*** Copy the property values of the given source bean into the given target bean.
*
*@paramsource source bean
*@paramtarget target bean
*@throwsException
* @Author YangXuyue*/
public static void copyProperties(Object source, Object target) throwsException {//获取target object的beanInfo
BeanInfo beanInfo =Introspector.getBeanInfo(target.getClass());//获取target object的属性信息
PropertyDescriptor[] targetPds =beanInfo.getPropertyDescriptors();//target object的属性setter,source object的属性getter
Method writeMethod, readMethod;
PropertyDescriptor readPropertyDescriptor;for(PropertyDescriptor targetPd : targetPds) {
readPropertyDescriptor=getPropertyDescriptor(source.getClass(), targetPd.getName());if (null ==readPropertyDescriptor) {continue;
}
readMethod=readPropertyDescriptor.getReadMethod();
writeMethod=targetPd.getWriteMethod();//Object类中不存在setClass方法
if (null == writeMethod || null ==readMethod) {continue;
}//如果getter方法不是public类型,设置accessible为true
if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
readMethod.setAccessible(true);
}//执行getter方法获取数值
Object value =readMethod.invoke(source);//如果setter方法不是public类型,设置accessible为true
if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {
writeMethod.setAccessible(true);
}//赋值
writeMethod.invoke(target, value);
}
}/*** 根据propertyName获取目标class的propertyDescriptor信息
*
*@paramclazz 目标class对象
*@parampropertyName 目标属性名称
*@return
*/
private static PropertyDescriptor getPropertyDescriptor(Class>clazz, String propertyName) {
PropertyDescriptor descriptor= null;try{
descriptor= newPropertyDescriptor(propertyName, clazz);
}catch(IntrospectionException e) {
LOGGER.warn("can‘t find the property what name is {} in {}", propertyName, clazz);
}returndescriptor;
}public static void main(String[] args) throwsException {//source bean
User user = newUser();
user.setId(1L);
user.setUserName("yangxuyue");//target bean
Role role = newRole();//copy properties
copyProperties(user, role);
System.out.println(role);
}
}