反射的常用api方法
Method.invoke()//方法自己调用自己,方法调用必须通过object.method()方式,method对象本身是无法调用自己的。
Method.getParameterTypes() //获得参数类型
Method.getReturnType() //获得返回值类型
Method.getParameterCount() //获得方法的参数个数
Method.getName() //获得方法名称
Method.getExceptionTypes() //获得方法抛出哪些异常
method.getAnnotation() //获得注解
参考https://www.cnblogs.com/bitbitbyte/p/12536575.html获取父类的方法
自己工作的实际运用
private <T> void contrastValue(T newer,T older,StringBuilder sb){
Class<?> newClass = newer.getClass();
// 保存属性对象数组到列表
List<Field> newFieldsList = Lists.newArrayList();
// 遍历所有父类字节码对象
while (newClass!=null){
// 获取字节码对象的属性对象数组
Field[] declaredFields = newClass.getDeclaredFields();
//将`Filed[]`数组转换为`List<>`然后再将其拼接至`ArrayList`上
newFieldsList.addAll(Arrays.asList(declaredFields));
// 获得父类的字节码对象
newClass = newClass.getSuperclass();
}
List<Field> oldFieldsList = Lists.newArrayList();
Class<?> oldClass = older.getClass();
// 遍历所有父类字节码对象
while (oldClass!=null){
// 获取字节码对象的属性对象数组
Field[] declaredFields = oldClass.getDeclaredFields();
//将`Filed[]`数组转换为`List<>`然后再将其拼接至`ArrayList`上
oldFieldsList.addAll(Arrays.asList(declaredFields));
// 获得父类的字节码对象
oldClass = oldClass.getSuperclass();
}
try {
for (Field field : newFieldsList) {
//反射时访问私有变量
field.setAccessible(true);
String newName = field.getName();
if (field.get(newer)!=null){
ApiModelProperty annotation = field.getAnnotation(ApiModelProperty.class);
for (Field oldField : oldFieldsList) {
oldField.setAccessible(true);
String oldName = oldField.getName();
if (oldName.equals(newName)){
sb.append(annotation.value()+":"+field.get(newer) + " => " + oldField.get(older) + ";" );
System.out.println(sb);
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}