java 获取类和父类的属性和方法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wangjun5159/article/details/79289244

问题

在日常开发中,经常需要获取当前类和父类的所有属性,没办法只能查API了。

getDeclaredFields VS getFields

查阅API得知,class.getDeclaredFields()能获取所有属性(public、protected、default、private),但不包括父类属性,相对的class.getFields() 获取类的属性(public),包括父类;
显然以上二者都不能满足需求,这么常见的需求,肯定有开源包实现了,功夫不负有心人果然查到了。apache commons包下的FieldUtils.getAllFields()可以获取类和父类的所有(public、protected、default、private)属性。

为了加深理解,看一下源码

 public static Field[] getAllFields(final Class<?> cls) {
        final List<Field> allFieldsList = getAllFieldsList(cls);
        return allFieldsList.toArray(new Field[allFieldsList.size()]);
    }
public static List<Field> getAllFieldsList(final Class<?> cls) {
        Validate.isTrue(cls != null, "The class must not be null");
        final List<Field> allFields = new ArrayList<Field>();
        Class<?> currentClass = cls;
        while (currentClass != null) {
            final Field[] declaredFields = currentClass.getDeclaredFields();
            for (final Field field : declaredFields) {
                allFields.add(field);
            }
            currentClass = currentClass.getSuperclass();
        }
        return allFields;
    }

通过class.getDeclaredFields()获取所有的属性,然后再获取类的父类,再获取所有属性,直到父类为null截止;

获取类和父类的方法

类似的,API中也有getDeclaredMethods()和getMethods()
class.getDeclaredMethods() 获取类的所有方法(public、protected、default、private),但不包括继承的方法;
class.getMethods() 获取当前类和父类的public方法。
apache commons包提供了MethodUtils.getMethodsWithAnnotation(class,annotation),获取类及父类的注解为annotation的public方法;

总结

  • 获取类的所有属性(public、protected、default、private),包括父类的属性,则使用FieldUtils.getAllFields()
  • 获取类标注某个注解的方法(包括类及父类),使用MethodUtils.getMethodsWithAnnotation(class,annotation)

猜你喜欢

转载自blog.csdn.net/wangjun5159/article/details/79289244
今日推荐