A way to initialize javabean random values

I was looking for some useful class / code that would take a java bean and initialize all its values โ€‹โ€‹with random values. This can be done by reflection, as some libraries already create toString () or equals () methods. This is useful when designing a user interface to have some data, for example.

Other possible nice things:

  • recursively initialize non-primitive or simple (strings, dates) members too
  • initialize beans collection
  • might give some way to limit the generated values, for example, for numbers we could give ranges, for regular expression strings or wildcards ...

Does anyone know something like this? thanks

EDIT: permission ... Got an Apocalisp sample that works and is finally what I was looking for. He has some disadvantages IMHO:

  • The library has much more features than use, but for me this is not a problem.
  • Itโ€™s quite difficult to understand how to create arbitrary objects for yours if you do not spend some time studying all this. This is a flaw.
  • And it may be more succint, I think, but that is good too.

thanks!

+4
source share
6 answers

Take a look at the Gen class from the Reductio library . This is part of a highly customizable structure for generating arbitrary values โ€‹โ€‹of more or less any type. Generators for primitive types and most classes of Java collections are provided. You should be able to instantiate Arbitrary for your classes quite easily.

EDIT Here is an example, adjusted:

 import static fj.test.Arbitrary.*; import static fj.Function.*; static final Arbitrary<Person> personArbitrary = arbitrary(arbInteger.gen.bind(arbString.gen, arbBoolean.gen, curry(new F3<Integer, String, Boolean, Person>() { public Person f(final Integer age, final String name, final Boolean male) {return new Person(age, name, male);}}))); 

Then create an arbitrary Face of size "100". That is, it will have a name of no more than 100 characters.

 Person p = personArbitrary.gen.gen(100, Rand.standard); 
+1
source

Take a look at Random Beans:

https://github.com/benas/random-beans

It allows you to populate a graph of Java objects with random data.

Hope this helps

Yours faithfully

+3
source

While I noticed that this post may be a little old, I just had the same need, and none of the solutions presented seemed to solve it, so I made a few quick fifteen-minute not quite general utility methods for generating randomly filled beans, which may or may not be useful to someone else who has a similar problem:

 import java.beans.PropertyDescriptor; import java.math.BigDecimal; import java.math.RoundingMode; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.Date; import java.util.Random; import org.springframework.beans.BeanUtils; public class RandomBeanUtil { public static <T> Collection<T> generateTestData(Class<T> clazz, int quantity) { Collection<T> list = new ArrayList<T>(); PropertyDescriptor[] descriptors = BeanUtils.getPropertyDescriptors(clazz); Random rand = new Random(); Calendar cal = Calendar.getInstance(); cal.set(Calendar.HOUR, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); try { for (int i = 0; i != quantity; i++) { T o = clazz.newInstance(); for (PropertyDescriptor descriptor : descriptors) { Class<?> type = descriptor.getPropertyType(); if (String.class.isAssignableFrom(type)) { descriptor.getWriteMethod().invoke(o, String.valueOf(new char[]{ (char)('A' + rand.nextInt(26)), (char)('a' + rand.nextInt(26)) })); } else if (Date.class.isAssignableFrom(type)) { cal.add(Calendar.DATE, rand.nextInt(60) - 30); descriptor.getWriteMethod().invoke(o, cal.getTime()); } else if (BigDecimal.class.isAssignableFrom(type)) { descriptor.getWriteMethod().invoke(o, new BigDecimal(rand.nextDouble() * 500).setScale(2, RoundingMode.HALF_UP)); } } list.add(o); } } catch (Exception e) { // TODO: Improve exception handling throw new RuntimeException("Error while generating the bean collection", e); } return list; } } 
+1
source

I don't have a library for you, but if you get a random generator, then perhaps this class may come in handy:

 public class BeanMethodIterator implements Iterable<Method> { private static final int MODIFIER_FILTER = (Modifier.PUBLIC | Modifier.STATIC); private static final int MODIFIER_EXPECTED = Modifier.PUBLIC; /** * Indicator to filter getter or setter methods. */ public enum Filter { /** Only getter methods. */ GETTERS(new Transform<Method, Boolean>(){ public Boolean transform(Method input) { return (input.getName().startsWith("get") || input.getName().startsWith("is")) && input.getParameterTypes().length == 0; }; }), /** Only setter methods. */ SETTTERS(new Transform<Method, Boolean>(){ public Boolean transform(Method input) { return input.getName().startsWith("set") && input.getParameterTypes().length == 1; }; }), /** Getter and setter methods. */ BOTH(new Transform<Method, Boolean>(){ public Boolean transform(Method input) { return Filter.SETTTERS.condition.transform(input) || Filter.GETTERS.condition.transform(input); }; }); private Transform<Method, Boolean> condition; private Filter(Transform<Method, Boolean> condition) { this.condition = condition; } }; /** * Iterate parent methods also? */ public enum Scope { PARENTS_ALSO() { @Override protected Method[] getMethods(Class<?> c) { return c.getMethods(); }; }, THIS_CLASS_ONLY() { @Override protected Method[] getMethods(Class<?> c) { return c.getDeclaredMethods(); } }; protected abstract Method[] getMethods(Class<?> c); } private final Filter filter; private final Scope scope; private final Class<?> theClass; /** * Constructor. * * @param theClass * @param what */ public BeanMethodIterator(Class<?> theClass, Filter what, Scope scope) { this.filter = what; this.theClass = theClass; this.scope = scope; } /** * Constructor. */ public BeanMethodIterator(Class<?> theClass) { this(theClass, Filter.BOTH, Scope.PARENTS_ALSO); } /** * Tells if a method is public * @param method * @return */ private static boolean isPublic(Method method) { return (method.getModifiers() & MODIFIER_FILTER) == MODIFIER_EXPECTED; } /** * {@inheritDoc} * @see java.lang.Iterable#iterator() */ public Iterator<Method> iterator() { final Method[] methods = this.scope.getMethods(this.theClass); return new Iterator<Method>() { int index = 0; public boolean hasNext() { while (index < methods.length) { if (isPublic(methods[index]) && filter.condition.transform(methods[index])) return true; index++; } return false; } public Method next() { if (!hasNext()) throw new NoSuchElementException(); return methods[index++]; } public void remove() { throw new UnsupportedOperationException(); } }; } public static void main(String[] args) { for (Method m: new BeanMethodIterator(Date.class, Filter.GETTERS, Scope.THIS_CLASS_ONLY)) { System.out.println(m.getName()); } } } /** * Represents a function that takes one input and returns a transformation of that input value ie * a transformation. The name Transform is used because it is shorter. * * @author Hannes de Jager * @since 01 Sep 2008 */ interface Transform<I, O> { /** * Invokes the function, performing the transformation, to produce an interpreted value. * * @param input the input value. * @return The computed result. */ public O transform(I input); } 
0
source

Apache Commons BeanUtils ( http://commons.apache.org/beanutils ) may be useful to you. There is no utility that you could use outside the box , but I think that all the building blocks are there, that is, access to properties, random generators.

0
source

You can do what you would like to do with the open source InPUT library. It uses range definitions based on XML descriptors, not definitions in code. InPUT uses the injection method and constructor, supporting complex object structures with arbitrary initialization depth. Examples and tutorials are available.

0
source

All Articles