使用Java注解与反射机制,比较两个对象属性的变化
自定义java注解
使用注解
利用java反射机制获取属性域
使用java的注解与反射机制,对同属一个类的两个对象的属性进行比较
自定义java注解
** 自定义注解,标记类中所需要对比的属性 **
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnotation {
public String action();
}
使用注解
在对象类中,使用注解标记所需要比对的属性
public class Apple {
@MyAnotation(action="颜色变化")
private String color;
@MyAnotation(action="价格变化")
private int price;
@MyAnotation(action="名字变化")
private String name;
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
利用java反射机制获取属性域
public class AnotationTest {
public static Map> getDifferent(Apple a1, Apple a2) throws IntrospectionException, IllegalArgumentException, IllegalAccessException, InvocationTargetException{
Map> map = new HashMap>();
Class clazz = Apple.class;
//获取当前类的实例域
Field[] fields = clazz.getDeclaredFields();
for(Field f : fields){
//获取该实例域上的注解
MyAnotation annotation = f.getAnnotation(MyAnotation.class);
if(annotation == null){
continue;
}
//获取注解中的内容
String action = annotation.action();
//使用javeBean PropertyDescriptor类型 获取bean的get方法
PropertyDescriptor pd = new PropertyDescriptor(f.getName(), clazz);
//获取get方法
Method readMethod = pd.getReadMethod();
Object o1 = readMethod.invoke(a1);
Object o2 = readMethod.invoke(a2);
if(o1==null && o2==null){
continue;
}
if(o1==null || o2 ==null){
Listlist = new ArrayList();
list.add(o1);
list.add(o2);
map.put(action, list);
continue;
}
if(!o1.equals(o2)){
Listlist = new ArrayList();
list.add(o1);
list.add(o2);
map.put(action, list);
continue;
}
}
return map;
}
public static void main(String[] args) throws IllegalArgumentException, IntrospectionException, IllegalAccessException, InvocationTargetException {
Apple a1 = new Apple();
a1.setColor("red");
a1.setName("烟台苹果");
Apple a2 = new Apple();
a2.setColor("yellow");
a2.setName("山西苹果");
Map> map = getDifferent(a1, a2);
if(!map.isEmpty()){
for(String s : map.keySet()){
System.out.println(s+":" + map.get(s).get(0)+"-"+map.get(s).get(1));
}
}
}
}