首页 > 编程语言 >javamock生成对象

javamock生成对象

时间:2023-04-23 14:47:08浏览次数:37  
标签:clazz nextInt 对象 getType else instance javamock 生成 class

`import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

public class Mock {

private static final Boolean[] bools                 = new Boolean[] { true, false };

private static final char[]    words                 = new char[] { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i',
        'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' };

private static final Random    r                     = new Random();

private static final int       MAX_COLLECTION_LENGTH = 50;

private static final int       MAX_STRING_LENGTH     = 30;

@SuppressWarnings({ "unchecked", "rawtypes" })
public static <T> T mock(Class<T> clazz) {
    if (clazz == Character.class || clazz == Character.TYPE) {
        return (T) (Character) words[r.nextInt(words.length)];
    } else if (clazz == Boolean.class || clazz == Boolean.TYPE) {
        return (T) (Boolean) bools[r.nextInt(bools.length)];
    } else if (clazz == Long.class || clazz == Long.TYPE) {
        return (T) (Long) r.nextLong();
    } else if (clazz == Integer.class || clazz == Integer.TYPE) {
        return (T) (Integer) r.nextInt();
    } else if (clazz == Short.class || clazz == Short.TYPE) {
        return (T) (Short) new Integer(r.nextInt(127)).shortValue();
    } else if (clazz == Float.class || clazz == Float.TYPE) {
        return (T) (Float) r.nextFloat();
    } else if (clazz == Double.class || clazz == Double.TYPE) {
        return (T) (Double) r.nextDouble();
    } else if (clazz == String.class) {
        return (T) randString(r.nextInt(MAX_STRING_LENGTH));
    }

    try {
        T instance = clazz.newInstance();

        for (Field f : ReflectUtil.getFields(clazz)) {
            f.setAccessible(true);
            Length lengthAnno = f.getAnnotation(Length.class);

            if (f.getType() == Character.TYPE) {
                f.setChar(instance, words[r.nextInt(words.length)]);
            } else if (f.getType() == Character.class) {
                f.set(instance, words[r.nextInt(words.length)]);
            } else if (f.getType() == Boolean.TYPE) {
                f.setBoolean(instance, bools[r.nextInt(bools.length)]);
            } else if (f.getType() == Boolean.class) {
                f.set(instance, bools[r.nextInt(bools.length)]);
            } else if (f.getType() == Long.TYPE) {
                f.setLong(instance, r.nextLong());
            } else if (f.getType() == Long.class) {
                f.set(instance, r.nextLong());
            } else if (f.getType() == Integer.TYPE) {
                f.setInt(instance, r.nextInt());
            } else if (f.getType() == Integer.class) {
                f.set(instance, r.nextInt());
            } else if (f.getType() == Short.TYPE) {
                f.setShort(instance, new Integer(r.nextInt(127)).shortValue());
            } else if (f.getType() == Short.class) {
                f.set(instance, new Integer(r.nextInt(127)).shortValue());
            } else if (f.getType() == Float.TYPE) {
                f.setFloat(instance, r.nextFloat());
            } else if (f.getType() == Float.class) {
                f.set(instance, r.nextFloat());
            } else if (f.getType() == Double.TYPE) {
                f.setDouble(instance, r.nextDouble());
            } else if (f.getType() == Double.class) {
                f.set(instance, r.nextDouble());
            } else if (f.getType() == String.class) {
                f.set(instance, randString(r.nextInt(MAX_STRING_LENGTH)));
            } else if (f.getType() == List.class) {
                int size = r.nextInt(MAX_COLLECTION_LENGTH);
                List<Object> list = new ArrayList<Object>(size);
                ParameterizedType pt = null;
                for (int i = 0; i < size; i++) {
                    pt = (ParameterizedType) f.getGenericType();
                    list.add(mock((Class) pt.getActualTypeArguments()[0]));
                }
                f.set(instance, list);
            } else if (f.getType() == Map.class) {
                int size = r.nextInt(MAX_COLLECTION_LENGTH);
                Map<Object, Object> map = new HashMap<Object, Object>();
                ParameterizedType pt = null;
                for (int i = 0; i < size; i++) {
                    pt = (ParameterizedType) f.getGenericType();
                    map.put(mock((Class) pt.getActualTypeArguments()[0]),
                            mock((Class) pt.getActualTypeArguments()[1]));
                }
                f.set(instance, map);
            } else if (f.getType() == Date.class) {
                f.set(instance, new Date());
            } else {
                f.set(instance, mock(f.getType()));
            }
        }

        return instance;
    } catch (Exception e) {
        throw new IllegalArgumentException(e);
    }
}

private static String randString(int count) {
    if (count == 0) {
        count = 1;
    }

    int length = words.length;
    char[] text = new char[count];
    for (int i = 0; i < count; i++) {
        text[i] = words[r.nextInt(length)];
    }

    return new String(text);
}

}

`

标签:clazz,nextInt,对象,getType,else,instance,javamock,生成,class
From: https://www.cnblogs.com/codeLearn/p/17346484.html

相关文章

  • Python生成requirements.txt方法
    Python生成requirements.txt方法 requirements.txt可以通过pip命令自动生成和安装,这种情况更适用于此项目是单独的虚拟python环境,生成requirements.txt文件。安装requirements.txt依赖:pipinstall-rrequirements.txt1.方法1:生成requirements.txt文件pipfreeze>re......
  • ExtJS 生成 UUID
    更新记录2023年4月23日初始化。ExtJS教程汇总:https://www.cnblogs.com/cqpanda/p/16328016.html生成UUIDletuuid=Ext.data.identifier.Uuid.create().generate();......
  • jmeter3.0 以上生成报告
    在cmd中执行 先进入到jmeter/bin目录中执行这个命令就可以生成已output命名的文件,里面有html的报告jmeter-n-t<testJMXfile>-l<testlogfile>-e-o<Pathtooutputfolder>jmeter-n-ttest.jmx-ltestReport-e-o./output 第二种方法命令先执行jmeter-n......
  • 测试环境服务器配置、生成环境服务器配置、测试机配置
    测试环境服务器配置:CPU:2核  内存:4GB(I/O优化)带宽5Mbps生产环境服务器配置:前端服务器3台配置CPU:4核  内存:4GB 带宽20Mbps;后端2台配置 CPU:4核  内存:8GB 带宽5Mbps测试机配置:CPU:8核内存:16G Speed:1000Mb/s......
  • java基础-面向对象-多态(四)
    某一个事务不同的体现形态例如:人:男人、女人动物:猫、狗猫x=new猫();动物x=new猫();1、多态的体现父类的引用指向了自己的子类对象父类的引用也可以接受自己的子类对象2、多态的前提必须是类与类之间有关系,要么继承、要么实现,通常还有一个前提,存在覆盖3、多态的好处多态的出现大大......
  • java基础-面向对象-继承(三)
    This  Super  继承的时候出现的两个关键字,final(不让复写方法)  abstract (必须复写方法)interface(修饰类)  implement继承好处:提高代码的复用性, 让类与类之间产生了关系,提供了另一个特征多态的前提父类的由来,其实是由多个类不断向上抽取共性内容而来的java来说,继承是单......
  • python 操作阿里云oss 对象存储上传下载文件
    python操作阿里云对象存储oss阿里云账号要有操作oss权限安装OSSSDKpipinstalloss2上传文件#-*-coding:utf-8-*-importoss2importos#阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控......
  • List嵌套排序并取第一个对象
    usingNewtonsoft.Json;using嵌套List排序;//示例listvarexampleString="{\"code\":1,\"msg\":\"[OK]AI诊断成功!\",\"diagnoseJson\":{\"disease\":{\"zhongda\":[[\"胆癌(胆囊癌胆总管癌胆囊肉瘤)\&q......
  • jackson将java对象转换为json字符串
    1.1. 下载jacksonJackson可以轻松的将Java对象转换成json对象和xml文档,同样也可以将json、xml转换成Java对象。相比json-lib框架,Jackson所依赖的jar包较少,简单易用并且性能也要相对高些。而且Jackson社区相对比较活跃,更新速度也比较快。下载地址:http://jackson.codehaus.org/1......
  • Unity框架:JKFrame2.0学习笔记(十)——自动生成资源引用代码(2)
    前言上一篇记录了自动生成资源引用代码的内部实现,主要是针对addressable的资源系统的,为了在加载时不会因为名字写错,加载错,也更加方便的使用addressable加载,这一篇记录下如何使用。如何使用之前看过,在编辑器中添加了工具按钮我们可以在addressable的groups面板上添加几个测试资源我......