All Downloads are FREE. Search and download functionalities are using the official Maven repository.

se.hiq.oss.commons.reflection.util.FieldUtils Maven / Gradle / Ivy

The newest version!
package se.hiq.oss.commons.reflection.util;

import java.lang.reflect.Field;
import java.util.HashSet;
import java.util.Set;

import se.hiq.oss.commons.reflection.filter.FieldFilter;

public final class FieldUtils {

    private FieldUtils() {
    }


    /**
     * Returns a set of all fields matching the supplied filter
     * declared in the clazz class.
     *
     * @param clazz  The class to inspect.
     * @param filter Filter to use.
     * @return All matching fields declared by the clazz class.
     **/
    public static Set getDeclaredFields(Class clazz, FieldFilter filter) {
        Set fields = new HashSet();
        Field[] allFields = clazz.getDeclaredFields();
        for (Field field : allFields) {
            if (filter.apply(field)) {
                fields.add(field);
            }
        }
        return fields;
    }

    /**
     * Returns a set of all fields matching the supplied filter
     * declared in the target class or any of its super classes.
     *
     * @param target Class to inspect.
     * @param filter Filter to use.
     *
     * @return All matching fields declared by the target class.
     **/
    public static Set getFields(Class target, FieldFilter filter) {
        Class clazz = target;
        Set fields = getDeclaredFields(clazz, filter);
        while ((clazz = clazz.getSuperclass()) != null) {
            fields.addAll(getDeclaredFields(clazz, filter));
        }
        return fields;
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy