在开发中有时候会通过反射操作包含集合的类,直接上代码
private static void encryptField(Object encryptObject) {
Class<?> infoClass = encryptObject.getClass();
//获取所有属性包括父类
List<Field> allField= new ArrayList<>();
while (infoClass != null) { // 遍历所有父类字节码对象
Field[] declaredFields = infoClass.getDeclaredFields();
try {
fieldsList.addAll(Arrays.asList(declaredFields)); //将`Filed[]`数组转换为`List<>`然后再将其拼接至`ArrayList`上
infoClass = infoClass.getSuperclass(); // 获得父类的字节码对象
} catch (Exception e) {
e.printStackTrace();
}
}
for (Field field : allField) {
field.setAccessible(true);
Object obj = field.get(encryptObject);
if (obj == null) {
continue;
}
//判断是否是集合类型
if (obj instanceof Collection) {
Collection<?> collection = (Collection<?>) obj;
for (Object o : collection) {
if (o != null) {
//递归
encryptField(o);
}
}
}
//后面就是具体业务功能操作
//该字段是否加了EncryptSwitch注解
if (field.isAnnotationPresent(EncryptSwitch.class)) {
System.out.println(field);
}
}
}