1. public class RandomObjectValue {
  2.  
  3. public static <T> T getObject(Class<?> clazz) {
  4. T t = null;
  5. if (clazz == null) {
  6. return t;
  7. }
  8. if((t = (T)getPrimitive(clazz))!= null){
  9. return t;
  10. }
  11. //需要有无参的构造器
  12. try {
  13. t = (T)clazz.newInstance();
  14. } catch (InstantiationException e) {
  15. e.printStackTrace();
  16. } catch (IllegalAccessException e) {
  17. e.printStackTrace();
  18. }
  19. Field[] fields = clazz.getDeclaredFields();
  20. //属性字段
  21. String fileName = "";
  22. //符合JavaBean规则的属性
  23. PropertyDescriptor property = null;
  24. //set方法对象
  25. Method method = null;
  26. for (int i = 0; i < fields.length; i++) {
  27. //属性字段
  28. fileName = fields[i].getName();
  29. //获取属性上的注解
  30. FormatAnnotation annotation = fields[i].getAnnotation(FormatAnnotation.class);
  31. try {
  32. property = new PropertyDescriptor(fileName, clazz);
  33. } catch (IntrospectionException e) {
  34. //没有设置set方法,或者不符合JavaBean规范
  35. continue;
  36. }
  37. //获取set方法对象
  38. method = property.getWriteMethod();
  39. //如果是字节类型(包含基本类型和包装类)
  40. if (fields[i].getType() == byte.class || fields[i].getType() == Byte.class) {
  41. try {
  42. method.invoke(t, SelfUtils.getByteValue());
  43. } catch (IllegalAccessException e) {
  44. e.printStackTrace();
  45. } catch (InvocationTargetException e) {
  46. e.printStackTrace();
  47. }
  48. }
  49. //如果是short类型(包含基本类型和包装类)
  50. else if (fields[i].getType() == short.class || fields[i].getType() == Short.class) {
  51. try {
  52. method.invoke(t, SelfUtils.getShortValue());
  53. } catch (IllegalAccessException e) {
  54. e.printStackTrace();
  55. } catch (InvocationTargetException e) {
  56. e.printStackTrace();
  57. }
  58. }
  59. //如果是char类型(包含基本类型和包装类)
  60. else if (fields[i].getType() == char.class || fields[i].getType() == Character.class) {
  61. try {
  62. method.invoke(t, SelfUtils.getCharValue());
  63. } catch (IllegalAccessException e) {
  64. e.printStackTrace();
  65. } catch (InvocationTargetException e) {
  66. e.printStackTrace();
  67. }
  68. }
  69. //如果是整型(包含基本类型和包装类)
  70. else if (fields[i].getType() == int.class || fields[i].getType() == Integer.class) {
  71. try {
  72. //为属性赋值
  73. method.invoke(t, SelfUtils.getIntValue());
  74. } catch (InvocationTargetException e) {
  75. e.printStackTrace();
  76. } catch (IllegalAccessException e) {
  77. e.printStackTrace();
  78. }
  79. }
  80. //如果是float(包含基本类型和包装类)
  81. else if (fields[i].getType() == float.class || fields[i].getType() == Float.class) {
  82. try {
  83. //为属性赋值
  84. method.invoke(t, SelfUtils.getFloatValue());
  85. } catch (InvocationTargetException e) {
  86. e.printStackTrace();
  87. } catch (IllegalAccessException e) {
  88. e.printStackTrace();
  89. }
  90. }
  91. //如果是double(包含基本类型和包装类)
  92. else if (fields[i].getType() == double.class || fields[i].getType() == Double.class) {
  93. try {
  94. //为属性赋值
  95. method.invoke(t, SelfUtils.getDoubleValue());
  96. } catch (InvocationTargetException e) {
  97. e.printStackTrace();
  98. } catch (IllegalAccessException e) {
  99. e.printStackTrace();
  100. }
  101. }
  102. //如果是double(包含基本类型和包装类)
  103. else if (fields[i].getType() == long.class || fields[i].getType() == Long.class) {
  104. try {
  105. //为属性赋值
  106. method.invoke(t, SelfUtils.getDoubleValue());
  107. } catch (InvocationTargetException e) {
  108. e.printStackTrace();
  109. } catch (IllegalAccessException e) {
  110. e.printStackTrace();
  111. }
  112. }
  113. //如果是boolean(包含基本类型和包装类)
  114. else if (fields[i].getType() == boolean.class || fields[i].getType() == Boolean.class) {
  115. try {
  116. //为属性赋值
  117. method.invoke(t, SelfUtils.getBooleanValue());
  118. } catch (InvocationTargetException e) {
  119. e.printStackTrace();
  120. } catch (IllegalAccessException e) {
  121. e.printStackTrace();
  122. }
  123. }
  124. //如果是boolean(包含基本类型和包装类)
  125. else if (fields[i].getType() == String.class) {
  126. try {
  127. //为属性赋值
  128. method.invoke(t, SelfUtils.getRamdomString(8));
  129. } catch (InvocationTargetException e) {
  130. e.printStackTrace();
  131. } catch (IllegalAccessException e) {
  132. e.printStackTrace();
  133. }
  134. }
  135. //如果是日期类型
  136. else if (fields[i].getType() == Date.class) {
  137. try {
  138. method.invoke(t, SelfUtils.getDateValue());
  139. } catch (IllegalAccessException e) {
  140. e.printStackTrace();
  141. } catch (InvocationTargetException e) {
  142. e.printStackTrace();
  143. }
  144. }
  145. //如果是List类型
  146. else if (fields[i].getType().isAssignableFrom(List.class)) {
  147. //获取泛型
  148. Type type = fields[i].getGenericType();
  149. //如果不是泛型,不做处理
  150. if (type == null) {
  151. continue;
  152. }
  153. if (type instanceof ParameterizedType) {
  154. ParameterizedType parameterizedType = (ParameterizedType)type;
  155. Class<?> genericClazz = (Class)parameterizedType.getActualTypeArguments()[0];
  156. int length = 0;
  157. String listLength = "4";
  158. if (annotation != null) {
  159. listLength = annotation.listLength();
  160. }
  161. if (StringUtils.isEmpty(listLength) || !listLength.matches(RegularExpression.allNumber)) {
  162. length = 4;
  163. }
  164. length = Integer.parseInt(listLength);
  165. List<Object> list = new ArrayList<>(length);
  166. for (int j = 0; j < length; j++) {
  167. list.add(getObject((Class<T>)genericClazz));
  168. }
  169. try {
  170. method.invoke(t, list);
  171. } catch (IllegalAccessException e) {
  172. e.printStackTrace();
  173. } catch (InvocationTargetException e) {
  174. e.printStackTrace();
  175. }
  176. }
  177. }
  178. //如果是Map类型
  179. else if(fields[i].getType().isAssignableFrom(Map.class)){
  180. //获取泛型
  181. Type types = fields[i].getGenericType();
  182. //如果不是泛型的话则不处理
  183. if(types == null){
  184. continue;
  185. }
  186. if(types instanceof ParameterizedType){
  187. int length = 4;
  188. if(annotation != null){
  189. String lengthStr = annotation.mapLength();
  190. if(!StringUtils.isEmpty(lengthStr) && lengthStr.matches(RegularExpression.allNumber)){
  191. length = Integer.parseInt(lengthStr);
  192. }
  193. }
  194. ParameterizedType parameterizedType = (ParameterizedType)types;
  195. Map<Object,Object> map = new HashMap();
  196. for(int j=0;j<length;j++){
  197. map.put(getObject((Class<?>)parameterizedType.getActualTypeArguments()[0]),
  198. getObject((Class<?>)parameterizedType.getActualTypeArguments()[1]));
  199. }
  200. try {
  201. method.invoke(t,map);
  202. } catch (IllegalAccessException e) {
  203. e.printStackTrace();
  204. } catch (InvocationTargetException e) {
  205. e.printStackTrace();
  206. }
  207. }
  208. }
  209. //这里默认处理的是自定义对象
  210. else {
  211. try {
  212. Object obj = getObject(fields[i].getType());
  213. method.invoke(t,obj);
  214. } catch (IllegalAccessException e) {
  215. e.printStackTrace();
  216. } catch (InvocationTargetException e) {
  217. e.printStackTrace();
  218. }
  219. }
  220. }
  221. return t;
  222. }
  223.  
  224. private static Object getPrimitive(Class<?> clazz) {
  225. //如果是byte类型(包含基本类型和包装类)
  226. if (clazz == byte.class || clazz == Byte.class) {
  227. return SelfUtils.getByteValue();
  228. }
  229. //如果是short类型(包含基本类型和包装类)
  230. if (clazz == short.class || clazz == Short.class) {
  231. return SelfUtils.getShortValue();
  232. }
  233. //如果是char类型(包含基本类型和包装类)
  234. if (clazz == char.class || clazz == Character.class) {
  235. return SelfUtils.getCharValue();
  236. }
  237. //如果是整型(包含基本类型和包装类)
  238. if (clazz == int.class || clazz == Integer.class) {
  239. //为属性赋值
  240. return SelfUtils.getIntValue();
  241. }
  242. //如果是float(包含基本类型和包装类)
  243. if (clazz == float.class || clazz == Float.class) {
  244. //为属性赋值
  245. return SelfUtils.getFloatValue();
  246. }
  247. //如果是double(包含基本类型和包装类)
  248. if (clazz == double.class || clazz == Double.class) {
  249. //为属性赋值
  250. return SelfUtils.getDoubleValue();
  251. }
  252. //如果是double(包含基本类型和包装类)
  253. if (clazz == long.class || clazz == Long.class) {
  254. //为属性赋值
  255. return SelfUtils.getDoubleValue();
  256. }
  257. //如果是boolean(包含基本类型和包装类)
  258. if (clazz == boolean.class || clazz == Boolean.class) {
  259. return SelfUtils.getBooleanValue();
  260. }
  261. //如果是boolean(包含基本类型和包装类)
  262. if (clazz == String.class) {
  263. //为属性赋值
  264. return SelfUtils.getRamdomString(8);
  265. }
  266. //如果是日期类型
  267. if (clazz == Date.class) {
  268. return SelfUtils.getDateValue();
  269. }
  270. return null;
  271. }
  272. }
  1. public class SelfUtils {
  2.  
  3. private static Random random = new Random();
  4.  
  5. private static char[] ch = {'A', 'B', 'C', 'D', 'E', 'F', 'G',
  6. 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b',
  7. 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w',
  8. 'x', 'y', 'z'};
  9. public static String getRamdomString(int length) {
  10. // char[] ch = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G',
  11. // 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y',
  12. // 'Z', 'a', 'b',
  13. // 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',
  14. // 'u', 'v', 'w',
  15. // 'x', 'y', 'z', 'o', '1'};
  16. if (length <= 0) {
  17. length = ch.length;
  18. }
  19. char[] chars = new char[length];
  20. for (int i = 0; i < length; i++) {
  21. chars[i] = ch[random.nextInt(ch.length)];
  22. }
  23. return new String(chars);
  24. }
  25.  
  26. public static int getIntValue() {
  27.  
  28. return random.nextInt(1000);
  29. }
  30.  
  31. public static byte getByteValue() {
  32. return (byte)(random.nextInt() & 0xEF);
  33. }
  34.  
  35. public static long getLongValue() {
  36.  
  37. return random.nextLong();
  38. }
  39.  
  40. public static short getShortValue() {
  41.  
  42. return (short)(random.nextInt() & 0xEFFF);
  43. }
  44.  
  45. public static float getFloatValue() {
  46.  
  47. return random.nextFloat();
  48. }
  49.  
  50. public static double getDoubleValue(){
  51.  
  52. return random.nextDouble();
  53. }
  54.  
  55. public static char getCharValue() {
  56.  
  57. return ch[random.nextInt(ch.length)];
  58. }
  59.  
  60. public static boolean getBooleanValue() {
  61.  
  62. return random.nextInt()%2 == 0;
  63. }
  64.  
  65. public static Date getDateValue() {
  66.  
  67. return new Date();
  68. }
  69. }
  1. import java.lang.annotation.ElementType;
  2. import java.lang.annotation.Retention;
  3. import java.lang.annotation.RetentionPolicy;
  4. import java.lang.annotation.Target;
  5.  
  6. @Retention(RetentionPolicy.RUNTIME)
  7. @Target(ElementType.FIELD)
  8. public @interface FormatAnnotation {
  9.  
  10. /**
  11. * 日期的格式
  12. * @return
  13. */
  14. String dateFormat() default "yyyy-MM-dd hh:mm:ss";
  15.  
  16. /**
  17. * list集合的长度
  18. * @return
  19. */
  20. String listLength() default "4";
  21.  
  22. /**
  23. * map集合的长度
  24. * @return
  25. */
  26. String mapLength() default "4";
  27. }
  1. public class RegularExpression {
  2.  
  3. public static final String allNumber = "[0-9]{1,}";
  4. }

https://blog.csdn.net/Procedure_monkey/article/details/80308253

java对象生成随意属性值的更多相关文章

  1. 【java】【反射】反射实现判断发生了修改操作,判断两个对象是否发生属性值的变更,判断两个List集合内对象的属性值是否发生变更

    java的反射实现: 判断发生了修改操作,判断两个对象是否发生属性值的变更,判断两个List集合内对象的属性值是否发生变更 今日份代码: package com.sxd.streamTest; imp ...

  2. 运行时给java对象动态的属性赋值

    运行时给java对象动态的属性赋值 如何给java对象动态的属性赋值(也就是在代码执行的时候才决定给哪个属性赋值)         1.自定义一个工具类ReflectHelper,代码如下所示: pa ...

  3. java中两个对象间的属性值复制,比较,转为map方法实现

    package com.franson.study.util; import java.lang.reflect.InvocationTargetException; import java.lang ...

  4. Java反射获取对象VO的属性值(通过Getter方法)

    有时候,需要动态获取对象的属性值. 比如,给你一个List,要你遍历这个List的对象的属性,而这个List里的对象并不固定.比如,这次User,下次可能是Company. e.g. 这次我需要做一个 ...

  5. 报表生成poi----java操作java对象生成execl表单

    1.Apache POI简介 Apache POI是Apache软件基金会的开放源码函式库,POI提供API给Java程式对Microsoft Office格式档案读和写的功能. .NET的开发人员则 ...

  6. JSON字符串反序列化成对象_部分属性值反序列化失败

    简介:本人在开发webapi接口时遇到了:一个复杂的Json字符串在反序列化为对象时报,无法发序列化其中的一个属性对象? 使用方法: InternalRecommendRequestFormModel ...

  7. [转]js对象中取属性值(.)和[ ]的区别

    原文地址:https://www.jianshu.com/p/6a76530e4f8f 今天在写js的过程中遇到这么一个问题,取一个对象的属性值,通过obj.keys怎么都取不出来,但是用obj[ke ...

  8. Java中生成一个唯一值的方式

    现总结几种生成一个唯一值的方式 第一种:采用nanoTime() // 理论上存在重复的可能,可以在后面再加上一个随机字符串 Random r = new Random(); for (int i = ...

  9. JAVA里List集合中的对象根据对象的某个属性值降序或者升序排序

    需要使用JDK1.8及以上 package com.stream; import java.util.Comparator; import java.util.List; public class T ...

随机推荐

  1. javaScript 一些小技巧

    日历 创建过去七天的数组,如果将代码中的减号换成加号,你将得到未来7天的数组集合 // 创建过去七天的数组 [...Array(7).keys()].map(days => new Date(D ...

  2. jQuery选择器与过滤器(二)

    一.jQuery选择器1.基本选择器:所有选择器    *标签选择器    标签名ID选择器    #ID类选择器    .className组合选择器    selector1,selector2 ...

  3. uni-app学习(二)

    1. uni-app学习(二) 1.1. 好用css记录 一定透明度的背景色background: rgba(255,255,255,.6); 1.2. 好用的代码段 store(用户登录) expo ...

  4. 28、IE报vuex requires a Promise polyfill in this browser问题解决

    解决方法第一步: 安装 babel-polyfill . babel-polyfill可以模拟ES6使用的环境,可以使用ES6的所有新方法 npm install --save babel-polyf ...

  5. C# 判断域名或ip+端口号 是否能正常连接?

    private static ManualResetEvent TimeoutObject = new ManualResetEvent(false); /// <summary> /// ...

  6. java并发值多线程同步业务场景以及解决方案

    1.20个人排队同时访问2个购票窗口,同时能购票的只有两个人,当其中一个人买票完成后,18个人中的其中一个在占用窗口进行购买. 20个人相当于20个线程,2相当于资源,当18个人等待的时候,相当于线程 ...

  7. 怎么解决前端线上Bug

    有一种八阿哥(Bug),叫"在我电脑上是好的呀". 有一种解决方式,叫"你去好好排查一下你自己的代码". 有一种控诉,叫"这绝不是后端的问题" ...

  8. Docker 0x01:Docker Container容器技术

    目录 Docker Container容器技术 一句话回答什么是容器? 为什么要有容器? 容器技术的影响 容器技术浅谈原理,怎么实现的?为什么能够这样轻量级标准化 难点 容器的标准 花边 Docker ...

  9. filter - date 日期插件

    为什么要用date插件: 我们希望日志展示的时间就是日志生成的时间,一般日志中都会附加时间,这样方便根据时间查找问题.但在logstash中,默认使用@timestamp时间值来表示日志的时间,@ti ...

  10. 基于gin框架搭建的一个简单的web服务

    刚把go编程基础知识学习完了,学习的时间很短,可能还有的没有完全吸收.不过还是在项目中发现知识,然后在去回顾已学的知识,现在利用gin这个web框架做一个简单的CRUD操作. 1.Go Web框架的技 ...