package com.yeejoin.amos.boot.biz.common.utils;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Objects;
import java.util.function.BiConsumer;

public class CommonUtils {

    /**
     * 带索引foreach
     *
     * @param <T>
     * @param startIndex 开始遍历的索引
     * @param elements   集合
     * @param action
     */
    public static <T> void forEach(int startIndex, Iterable<? extends T> elements, BiConsumer<Integer, ? super T> action) {
        Objects.requireNonNull(elements);
        Objects.requireNonNull(action);
        if (startIndex < 0) {
            startIndex = 0;
        }
        int index = 0;
        for (T element : elements) {
            index++;
            if (index <= startIndex) {
                continue;
            }

            action.accept(index - 1, element);
        }
    }

    public static Object getFiledValueByName(String filedName, Object o) throws InvocationTargetException, IllegalAccessException, NoSuchMethodException {
        String firstLetter = filedName.substring(0, 1).toUpperCase();
        String getterName = "get" + firstLetter + filedName.substring(1);
        Method method;
        method = o.getClass().getMethod(getterName, new Class[]{});
        Object value = method.invoke(o, new Object[]{});
        return value;
    }
}
