现象:
通过反射比较对象参数的不同
方法:
一、PropertyDescriptor类
PropertyDescriptor类表示JavaBean类通过存储器导出一个属性。主要方法:
1、getPropertyType(),获得属性的Class对象。
2、getReadMethod(),获得用于读取属性值的方法;getWriteMethod(),获得用于写入属性值的方法。
3、hashCode(),获取对象的哈希值。
4、setReadMethod(Method readMethod),设置用于读取属性值的方法;setWriteMethod(MethodwriteMethod),设置用于写入属性值的方法;
需要导包java.bean.*;
通过属性名获取对应的值,利用反射方法,如下:
ReflectPoint pt1 = new ReflectPoint(7,9);
String propertyName = “x”;//给一个属性,获取值
PropertyDescriptor pd = new PropertyDescriptor(propertyName,pt1.getClass());
Method methodGetX = pd.getReadMethod();//Read对应get()方法
Object reValue = methodGetX.invoke(pt1);
二、通过PropertyDescriptor类 得到类的读取方法(get)循环调用
三、建立对象调用 获取对象1的getName方法得到name的值
四、传入对象比较两个对象的参数是否相同
5、isAccessible()和setAccessible(true);
当isAccessible()的结果是false时不允许通过反射访问该字段
当该字段时private修饰时isAccessible()得到的值是false,必须要改成true才可以访问
所以 f.setAccessible(true);得作用就是让我们在用反射时访问私有变量
六:以上判读对象是否相等使用的是equals() 如果对象是BigDecimal 处理方式
判断数据类型如果是BigDecimal 则使用compareTo来判断
/**
* 比较两个对象某些参数是否变化
* @param o1 -对象1
* @param o2 -对象2
* @param props - 多参数比较的字段名称
*/
public static void change(Object o1, Object o2, String... props) {
//获取 Class对象
Class class1 = o1.getClass(),class2=o2.getClass();
//循环需要比较的参数名称
for (String prop : props) {
//得到PropertyDescriptor类
PropertyDescriptor p1 = BeanUtils.getPropertyDescriptor(class1, prop),
p2=BeanUtils.getPropertyDescriptor(class2, prop);
//得到读取方法(get方法)
Method getProp1 = p1.getReadMethod();
Method getProp2 = p2.getReadMethod();
try {
//判断属性是不是公共的不是公共的则禁用安全检查
if (!Modifier.isPublic(getProp1.getDeclaringClass().getModifiers())) {
//Accessable属性是继承自AccessibleObject类. 功能是启用或禁用安全检查
getProp1.setAccessible(true);
}
//调用get方法
Object invoke1 = getProp1.invoke(o1);
System.out.println(invoke1.toString());
if (!Modifier.isPublic(getProp2.getDeclaringClass().getModifiers())) {
getProp2.setAccessible(true);
}
Object invoke2 = getProp2.invoke(o2);
System.out.println(invoke2.toString());
if(invoke1.equals(invoke2)){
System.out.println("o1对象与o2对象"+prop+"参数相同");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static boolean compare(Object v1,Object v2){
if(v1 instanceof BigDecimal && v2 instanceof BigDecimal){//只有BigDecimal类型的不能用equals判断 BigDecimal出现null的走else也没问题
if(!(v1 == null ? v2 == null : ((BigDecimal) v1).compareTo((BigDecimal) v2) == 0))return true;
} else {
if (!(v1 == null ? v2 == null : v1.equals(v2))) return true;
}
return false;
}