/*
 * Copyright (c) 2009 JSCAPE
 * 1147 S. 53rd Pl., Mesa, Arizona, 85206, U.S.A.
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * JSCAPE. ("Confidential Information").  You shall not disclose such
 * Confidential Information and shall use it only in accordance with
 * the terms of the license agreement you entered into with JSCAPE.
 *
 */

package com.jscape.util.reflection;

import com.jscape.util.collections.Algorithms;
import com.jscape.util.functor.UnaryFunction;
import com.jscape.util.functor.UnaryPredicate;

import java.lang.reflect.Field;

import static com.jscape.util.Parameters.assertNotNull;

/**
 * @author Alex Usun
 */
public class FieldFinder
        extends UnaryFunction<Class, Field> {

    private final UnaryPredicate<? super Field> predicate;

    public static Field find(Class aClass, UnaryPredicate<? super Field> predicate) {
        if (aClass == null) {
            return null;
        }

        Field ret = Algorithms.find(aClass.getDeclaredFields(), predicate);

        return ret != null ? ret : find(aClass.getSuperclass(), predicate);
    }

    public FieldFinder(UnaryPredicate<? super Field> predicate) {
        assertNotNull(predicate);
        this.predicate = predicate;
    }

    public Field evaluate(Class value) {
        return find(value, this.predicate);
    }

    public String toString() {
        return "FieldFinder{"
                + "predicate=" + this.predicate
                + '}';
    }
}
