Bean 字段填充工具

package com.frank.utils;

import cn.hutool.core.util.RandomUtil;
import com.frank.reflect.Person;
import org.junit.Test;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class BeanTools {


    public static <T>  T getInstance(Class<T> c) throws InstantiationException, IllegalAccessException, InvocationTargetException {
        /**
         * 1. 得到类的所有方法
         * 2. 根据方法生成随机数
         * 3. 将生成的随机数赋值生成对象
         */
        T t = c.newInstance();
        for(Method method:t.getClass().getDeclaredMethods()){
            if(method.getName().startsWith("set")){
                Class<?> parameterType = method.getParameterTypes()[0];
                Object randomData = getRandomData(parameterType);
                method.invoke(t,randomData);
            }
        }
        return t;
    }


    /**
     * 实现类型和随机工具的匹配
     * @param t
     * @return
     * @param <T>
     */
    @Test
    public static <T> T getRandomData(Class<T> t){
        String name = t.getName();
        if(name.endsWith("String")){
            return (T) RandomUtil.randomString(10);
        } else if (name.endsWith("Integer")) {
            return (T)new Integer(RandomUtil.randomInt(10));
        } else if (name.endsWith("Float")) {
            return (T) "12.5";
        }else{
            return null;
        }
    }


}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值