示例:1获取类所有get,set方法
示例:2通过反射得到属性名称,获取属性get,set方法
// 获取所有类所有get set 方法
try {
Store store= new Store();
BeanInfo beanInfo = Introspector.getBeanInfo(Object.class);
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor ptors:propertyDescriptors) {
//读取get方法名 及内容
System.out.println(ptors.getReadMethod().getName()+"*****"+ptors.getReadMethod().invoke(store,null));
//读取set方法名 及设置值
System.out.println(ptors.getWriteMethod().getName()+"****"+ptors.getWriteMethod().invoke(store));
}
}catch (Exception e){
e.printStackTrace();
}
//通过属性获取属性的get,set方法
/**
* 通过内省复制一个新的类
* @param obj
* @return
* @throws Exception
*/
public static <T> T copyModel(Object obj){
T model = null;
try {
model = (T) obj.getClass().newInstance();
} catch (Exception e) {
e.printStackTrace();
return model;
}
try {
PropertyDescriptor propertyDescriptor;
Field[] fields = obj.getClass().getDeclaredFields();
for (Field field:fields) {
propertyDescriptor = new PropertyDescriptor(field.getName(), obj.getClass());//创建一个属性描述器
propertyDescriptor.getWriteMethod().invoke(model,propertyDescriptor.getReadMethod().invoke(obj));
}
return model;
}catch (Exception e){
return model;
}
}