JetBrains Academy: Reflection basics - Kamil-Jankowski/Learning-JAVA GitHub Wiki

JetBrains Academy: Reflection basics

Field count:

Implement getNumberOfFieldsClassDeclares method to count the number of fields declared in a class. You should count public, protected, default (package) access, and private fields, excluding inherited fields.

/**
 Get number of fields class declares (the ones inherited should be excluded).
 */
class FieldGetter {

    public int getNumberOfFieldsClassDeclares(Class<?> clazz) {
        return clazz.getDeclaredFields().length;
    }

}

Field count - 2:

Implement the getNumberOfAccessibleFields method to count the number of accessible public fields of the class or interface represented by the clazz object.

/**
 Get number of accessible public fields for a given class.
 */
class FieldGetter {

    public int getNumberOfAccessibleFields(Class<?> clazz) {
        return clazz.getFields().length;
    }

}