Beans Package
在编程的过程中,我们面对最多的就是Bean,所以我们要学会跟他交流
JDK 内置有处理Bean的包 java.beans.*
代码可以解释一切
Show code
package reflect;
public class Source {
private Integer id;
private String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
package reflect;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
public class BeanInfoTest {
public static void main(String[] args) throws Exception{
// 新建实体类,测试使用
Source source = new Source();
source.setId(1);
source.setName("xlroce");
// 构建BeanInfo 存放Bean信息
BeanInfo beanInfo = Introspector.getBeanInfo(Source.class);
//每一个PropertyDescriptor 应该存放field, setFieldMethod, getFieldMethod
//注意: 因为内置有Class属性,所有有getClass()方法,没setClass方法
PropertyDescriptor propertyDescriptors[] = beanInfo.getPropertyDescriptors();
for(PropertyDescriptor propertyDescriptor : propertyDescriptors){
//过滤class属性
if( !"class".equals(propertyDescriptor.getName())) {
System.out.println("field name : " + propertyDescriptor.getName());
//测试
Method getFieldMethod = propertyDescriptor.getReadMethod();
Object object = getFieldMethod.invoke(source);
System.out.println("field value: " + object);
}
}
}
}
field name : id
field value: 1
field name : name
field value: xlroce
实用栗子
一个Object bean参数过来,可以把它的参数输出出来.
如系统日志记录:
-
增加记录
who(user) + fieldName + fieldValue
-
修改记录
public static void compareBean(Object source, Object target) {
if (source.getClass() != target.getClass()) {
System.out.println("不同的bean");
} else {
try {
BeanInfo beanInfo = Introspector.getBeanInfo(Source.class);
//每一个PropertyDescriptor 应该存放field, setFieldMethod, getFieldMethod
//注意: 因为内置有Class属性,所有有getClass()方法,没setClass方法
PropertyDescriptor propertyDescriptors[] = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
//过滤class属性
if (!"class".equals(propertyDescriptor.getName())) {
System.out.println("field name : " + propertyDescriptor.getName());
//测试
Method getFieldMethod = propertyDescriptor.getReadMethod();
Object sourceObject = getFieldMethod.invoke(source);
Object targetObject = getFieldMethod.invoke(target);
if (null != sourceObject && !sourceObject.equals(targetObject)) {
System.out.println(propertyDescriptor.getName() + " 值: (" + sourceObject + ") 改: (" + targetObject + ")");
} else if (null == sourceObject && targetObject != null) {
System.out.println(propertyDescriptor.getName() + " 值: (" + "空" + ") 改: (" + targetObject + ")");
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
测试:
public static void main(String[] args) throws Exception {
Source source = new Source();
source.setId(1);
source.setName("xlroce");
Source target = new Source();
target.setId(1);
target.setName("roce");
compareBean(source,target);
}
结果:
name 值: (xlroce) 改: (roce)