Persimmonium Persimmonium - 2 years ago 97
Java Question

way to initialize a javabean to random values

I was looking for some utility class/code that would take a java bean and initialize all its values to random values. It could be done via reflection as some libraries already create the toString() or equals() methods. Is is useful while developing the UI to have some data for example.

Other possible nice to haves:

  1. recursively initialize non primitive or simple (string, date) members too

  2. initialize a collection of beans

  3. maybe give some way to limit the values generated, for example for numbers we could give ranges, for strings regexps or wildcards...

somebody knows something like this?

EDIT: resolving...Got Apocalisp's sample working and definitively is what I was looking for. It has some drawbacks IMHO:

  • The library has a much larger scope than that use, but this is not a problem for me

  • It's quite complicated to understand how to build the Arbitrary for your objects unless you invest some time to study the whole thing. This is a drawback.

  • And it could be more succint I guess, but that is fine too.


Answer Source

Take a look at the Gen class from the Reductio library. This is part of a highly configurable framework for generating arbitrary values of more or less any type. Generators for primitive types and most of the Java collections classes are provided. You should be able to create Arbitrary instances for your classes fairly easily.

EDIT Here's the example, corrected:

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 generate an arbitrary Person of "size 100" like so. I.e. it will have a name of 100 characters at most.

Person p = personArbitrary.gen.gen(100, Rand.standard);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download