java对比类代码 java对比文件是否一致( 二 )


package pojo;
/**
【java对比类代码 java对比文件是否一致】 * Created by liaokai on 2017/11/17 0017.
*/
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Person person = (Person) o;
if (age != person.age) return false;
return name != null ? name.equals(person.name) : person.name == null;
}
@Override
public int hashCode() {
int result = name != null ? name.hashCode() : 0;
result = 31 * result + age;
return result;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
package util;
import pojo.Person;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by liaokai on 2017/11/17 0017.
*/
public class CompareUtilT {
public ListMap compareT(T t1,T t2,String className){
ListMap list = new ArrayListMap();
//内容没改变直接返回
if(t1.equals(t2)){
return list;
}
try {
Class c = Class.forName(className);
//读取t1和t2中的所有属性
Field[] fields = c.getDeclaredFields();
for (int i = 0; ifields.length; i++) {
Field field =fields[i];
field.setAccessible(true);
Object value1=field.get(t1);
Object value2=field.get(t2);
//判断这两个值是否相等
if(!isValueEquals(value1,value2)){
Map map = new HashMap();
map.put("name",field.getName());
map.put("before",value1);
map.put("after",value2);
list.add(map);
}
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return list;
}
private boolean isValueEquals(Object value1, Object value2) {
if(value1==nullvalue2==null){
return true;
}
if(value1==nullvalue2!=null){
return false;
}
if(value1.equals(value2)){
return true;
}
return false;
}
}
package pojo;
import util.CompareUtil;
/**
* Created by liaokai on 2017/11/17 0017.
*/
public class Test {
public static void main(String[] args) {
Person p1 = new Person("张三",14);
Person p2 = new Person("张三",15);
Person p3 = new Person("李四",15);
CompareUtilPerson compareUtil = new CompareUtilPerson();
System.out.println(compareUtil.compareT(p1,p1,Person.class.getName()));
System.out.println(compareUtil.compareT(p1,p2,Person.class.getName()));
System.out.println(compareUtil.compareT(p1,p3,Person.class.getName()));
System.out.println(compareUtil.compareT(p2,p3,Person.class.getName()));
}
}
//运行结果
[]
[{before=14, name=age, after=15}]
[{before=张三, name=name, after=李四}, {before=14, name=age, after=15}]
[{before=张三, name=name, after=李四}]
java中不同类型数比大小的程序代码可以使用java.math.BigDecimal类型,把不同类型的数统一成这个类型,然后用compareTo方法比较,1、0、-1分别表示大于、等于、小于,例如:比较1.22 和 5 , 类声明和main方法声明略,直接写内容

推荐阅读