Search in sources :

Example 1 with ModelField

use of com.amplifyframework.core.model.annotations.ModelField in project amplify-android by aws-amplify.

the class FieldFinder method findNonTransientFieldsIn.

/**
 * Helper for finding all fields in a class without limiting to {@link ModelField}.
 * @param clazz clazz the Class object.
 * @return set of fields
 */
@NonNull
public static List<Field> findNonTransientFieldsIn(@NonNull Class<?> clazz) {
    final List<Field> fields = new ArrayList<>();
    Class<?> fieldContainerClazz = clazz;
    while (fieldContainerClazz != null) {
        for (Field field : fieldContainerClazz.getDeclaredFields()) {
            /*
                 * In Android 21+, java.lang.Object has two transient fields, shadow$_klass_ and shadow$_monitor_.
                 * They are not actually present when running unit tests, but only when running on an Android device.
                 * We don't care about them, so we will filter them out by ignoring all transient fields.
                 */
            if (!Modifier.isTransient(field.getModifiers())) {
                fields.add(field);
            }
        }
        fieldContainerClazz = fieldContainerClazz.getSuperclass();
    }
    Collections.sort(fields, Comparator.comparing(Field::getName));
    return Immutable.of(fields);
}
Also used : ModelField(com.amplifyframework.core.model.annotations.ModelField) Field(java.lang.reflect.Field) ArrayList(java.util.ArrayList) NonNull(androidx.annotation.NonNull)

Example 2 with ModelField

use of com.amplifyframework.core.model.annotations.ModelField in project amplify-android by aws-amplify.

the class FieldFinder method findModelFieldsIn.

/**
 * Get a set of all the fields of a class that are
 * annotated with {@link ModelField} annotation.
 *
 * @param clazz the Class object.
 * @return set of fields
 */
@NonNull
public static List<Field> findModelFieldsIn(@NonNull Class<?> clazz) {
    final List<Field> fields = new ArrayList<>();
    Class<?> fieldContainerClazz = clazz;
    while (fieldContainerClazz != null) {
        for (Field field : fieldContainerClazz.getDeclaredFields()) {
            if (field.isAnnotationPresent(ModelField.class)) {
                fields.add(field);
            }
        }
        fieldContainerClazz = fieldContainerClazz.getSuperclass();
    }
    Collections.sort(fields, (o1, o2) -> o1.getName().compareTo(o2.getName()));
    return Immutable.of(fields);
}
Also used : ModelField(com.amplifyframework.core.model.annotations.ModelField) Field(java.lang.reflect.Field) ArrayList(java.util.ArrayList) NonNull(androidx.annotation.NonNull)

Aggregations

NonNull (androidx.annotation.NonNull)2 ModelField (com.amplifyframework.core.model.annotations.ModelField)2 Field (java.lang.reflect.Field)2 ArrayList (java.util.ArrayList)2