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

net.thucydides.core.reflection.FieldFinder Maven / Gradle / Ivy

package net.thucydides.core.reflection;


import com.google.common.base.Optional;

import java.lang.reflect.Field;

public class FieldFinder {

    private final Class targetClass;

    private FieldFinder(Class targetClass) {
        this.targetClass = targetClass;
    }

    public static FieldFinder inClass(Class targetClass) {
        return new FieldFinder(targetClass);
    }


    public Optional findFieldCalled(String fieldName) {
        return findFieldCalled(fieldName, targetClass);
    }

    private Optional findFieldCalled(String fieldName, Class targetClass) {
        Field[] fields = targetClass.getDeclaredFields();
        for(Field field : fields) {
            if (field.getName().equals(fieldName)) {
                return Optional.of(field);
            }
        }
        if (targetClass.getSuperclass() != null) {
            return findFieldCalled(fieldName, targetClass.getSuperclass());
        }
        return Optional.absent();
    }

    public Optional findFieldOfType(Class type) {
        return findFieldOfType(type, targetClass);
    }

    private Optional findFieldOfType(Class type, Class targetClass) {
        Field[] fields = targetClass.getDeclaredFields();
        for(Field field : fields) {
            if (field.getType().equals(type)) {
                return Optional.of(field);
            }
        }
        if (targetClass.getSuperclass() != null) {
            return findFieldOfType(type, targetClass.getSuperclass());
        }
        return Optional.absent();
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy