package com.fjhx.utils;

import lombok.SneakyThrows;

import javax.validation.constraints.NotNull;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Objects;
import java.util.StringJoiner;
import java.util.stream.Collectors;

public class HxUtil {

    /**
     * list转str，用,拼接
     *
     * @param list list
     * @return 用 , 拼接list的数组
     */
    public static String listToStr(List<?> list) {
        StringJoiner joiner = new StringJoiner(",");
        list.stream().distinct().filter(Objects::nonNull).collect(Collectors.toList())
                .forEach(item -> joiner.add(item.toString()));

        return joiner.toString();
    }

    /**
     * 获取实体指定值的get方法
     */
    @SneakyThrows
    public static Object reflectGet(@NotNull Object obj, String name) {
        String methodName = "get" + firstUpperCase(name);
        Method method = obj.getClass().getMethod(methodName);
        method.setAccessible(true);
        return method.invoke(obj);
    }

    /**
     * 首字母大写
     *
     * @param str 需要首字母大写的字符串
     * @return 转换成首字母大写字母后的传入字符串
     */
    public static String firstUpperCase(String str) {
        char[] ch = str.toCharArray();
        if (ch[0] >= 'a' && ch[0] <= 'z') {
            ch[0] = (char) (ch[0] - 32);
        }
        return new String(ch);
    }

}
