使用java的内省
内省
概述:用来获得JavaBean的属性及属性的get或set方法
Introspector类
在 Java Bean 上进行内省,了解其所有属性、公开的方法和事件。
static BeanInfo getBeanInfo(Class<?> beanClass)
BeanInfo类
获得 beans PropertyDescriptor。
PropertyDescriptor[] getPropertyDescriptors()
PropertyDescriptor类
Method getReadMethod()
获得应该用于读取属性值的方法。 (getXxx)
Method getWriteMethod()
获得应该用于写入属性值的方法。 (setXxx)
工具类
public class MyBeanUtils {
public static void copyProperties(Object source,Object target) throws Exception {
if (source==null){
throw new Exception("Source can bot be null");
}
if (target==null){
throw new Exception("target can bot be null");
}
Class<?> sourceClazz = source.getClass();
Class<?> targetClazz = target.getClass();
if (!sourceClazz.equals(targetClazz)){
throw new Exception("类型不一致");
}
BeanInfo beanInfo = Introspector.getBeanInfo(source.getClass());
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor p:propertyDescriptors){
Method readMethod = p.getReadMethod();
Method writeMethod = p.getWriteMethod();
Object value = readMethod.invoke(source, new Object[]{});
if (value==null||readMethod.getName().equals("getClass")){
continue;
}
writeMethod.invoke(target,value);
}
}
}