以前遇到要获取当前类以及所有父类的的field的时候,都是递归一直往上找,一直到Object ,个人觉得这种方法是不是太low了,有没有更好的办法?或者jdk其实是有这种方法的,只是我不知道,今天看了下spring中的实现,也是一样的,真没有更好的办法?
public static void doWithFields(Class<?> clazz, ReflectionUtils.FieldCallback fc, @Nullable ReflectionUtils.FieldFilter ff) {
Class targetClass = clazz;
do {
Field[] fields = getDeclaredFields(targetClass);
Field[] var5 = fields;
int var6 = fields.length;
for(int var7 = 0; var7 < var6; ++var7) {
Field field = var5[var7];
if (ff == null || ff.matches(field)) {
try {
fc.doWith(field);
} catch (IllegalAccessException var10) {
throw new IllegalStateException("Not allowed to access field '" + field.getName() + "': " + var10);
}
}
}
targetClass = targetClass.getSuperclass();
} while(targetClass != null && targetClass != Object.class);
}
private static Field[] getDeclaredFields(Class<?> clazz) {
Assert.notNull(clazz, "Class must not be null");
Field[] result = (Field[])declaredFieldsCache.get(clazz);
if (result == null) {
try {
result = clazz.getDeclaredFields();
declaredFieldsCache.put(clazz, result.length == 0 ? NO_FIELDS : result);
} catch (Throwable var3) {
throw new IllegalStateException("Failed to introspect Class [" + clazz.getName() + "] from ClassLoader [" + clazz.getClassLoader() + "]", var3);
}
}
return result;
}