Class Instancio

java.lang.Object
org.instancio.Instancio

public final class Instancio extends Object
Instancio API for creating instances of a class.

Usage

Create and populate an instance of a class

Returns an object fully populated with random data with non-null values.

 Person person = Instancio.create(Person.class);
 

Customise object's values

Returns an object populated with random data and some specified fields' values customised.

 // Customise specific fields using set(), supply(), or generate()
 Person person = Instancio.of(Person.class)
     .set(field(Person::getFullName), "Homer Simpson")
     .supply(all(LocalDateTime.class), () -> LocalDateTime.now())
     .generate(field(Phone::getNumber), gen -> gen.text().pattern("(#d#d#d) #d#d#d-#d#d#d#d"))
     .create();
 

Allow null values to be generated

By default, Instancio populates every field with non-null values. Specifying fields as nullable allows them to be randomly assigned either null or non-null values.

 Person person = Instancio.of(Person.class)
     .withNullable(field(Person::getDateOfBirth))
     .withNullable(all(Gender.class))
     .withNullable(allStrings())
     .create();
 

Ignore certain fields or classes

Ignored fields will not be populated. Their values will be null (unless they have a default value assigned).

 Person person = Instancio.of(Person.class)
     .ignore(fields().named("id"))  // Person.id, Address.id, etc.
     .ignore(all(LocalDateTime.class))
     .create();
 

Creating instances of a class from a Model

Parameters from the Instancio builder API can be saved as a Model object using the InstancioApi.toModel() method. Objects can subsequently be generated based on this model. Models are useful for:
  • Serving as prototypes for creating customised instances of a class, allowing model parameters to be overridden.
  • Reducing code duplication by reusing models across different parts of the codebase.

 // Create a reusable model to standardise certain values
 Model<Person> simpsons = Instancio.of(Person.class)
     .supply(all(Address.class), () -> new Address("742 Evergreen Terrace", "Springfield", "US"))
     .supply(field(Person::getPets), () -> List.of(
                  new Pet(PetType.CAT, "Snowball"),
                  new Pet(PetType.DOG, "Santa's Little Helper"))
     // Additional specifications...
     .toModel();

 // The toModel() method allows you to save the builder configurations inside
 // a reusable template. You can then generate objects from the model directly
 // or modify it to override certain values, e g. use the above model as is:
 Person person = Instancio.create(simpsons);

 // Use the model but override the name:
 Person homer = Instancio.of(simpsons).set(field(Person::getName), "Homer").create();
 Person marge = Instancio.of(simpsons).set(field(Person::getName), "Marge").create();

 // A model can also used to create another model.
 // This snippet creates a new model from the original model to include a new pet.
 Model<Person> withNewPet = Instancio.of(simpsons)
     .supply(field(Person::getPets), () -> List.of(
                  new Pet(PetType.PIG, "Plopper"),
                  new Pet(PetType.CAT, "Snowball"),
                  new Pet(PetType.DOG, "Santa's Little Helper"))
     .toModel();
 

Creating generic classes

You can create instances of generic types using two approaches.

Option 1: using a TypeToken


 Pair<Apple, Banana> pairOfFruits = Instancio.create(new TypeToken<Pair<Apple, Banana>>() {}); // note the empty '{}' braces
 

Creates a Pair object with specific type arguments (Apple and Banana) using TypeToken.

Option 2: using withTypeParameters to specify the type arguments

This approach allows arbitrary type parameters to be specified at runtime. However, using this method may result in an "unchecked assignment" warning.


 Pair<Apple, Banana> pairOfFruits = Instancio.of(Pair.class)
     .withTypeParameters(Apple.class, Banana.class)
     .create();
 
Since:
1.0.1
See Also:
  • Method Details

    • create

      public static <T> T create(Class<T> type)
      Creates an instance of the specified class.
      Type Parameters:
      T - the type of object
      Parameters:
      type - to create
      Returns:
      an object of the specified type
      Since:
      1.0.1
    • createBlank

      @ExperimentalApi public static <T> T createBlank(Class<T> type)
      Creates a blank object of the specified class.

      The created object will have the following properties:

      • value fields (strings, numbers, dates, etc) are null
      • arrays, collections, and maps are empty
      • nested POJOs are blank

      For example, assuming the following POJO:

      
       class Person {
           String name;
           LocalDate dateOfBirth;
           List<Phone> phoneNumbers;
           Address address;
       }
       

      Creating a blank Person object will produce:

      
       Person person = Instancio.createBlank(Person.class);
      
       // Output:
       // Person[
       //   name=null,
       //   dateOfBirth=null,
       //   phoneNumbers=[] // empty List
       //   address=Address[street=null, city=null, country=null] // blank nested POJO
       // ]
       
      Type Parameters:
      T - the type of object
      Parameters:
      type - the type of blank object to create
      Returns:
      a blank object of the specified type
      Since:
      4.7.0
      See Also:
    • createList

      public static <T> List<T> createList(Class<T> elementType)
      Creates a List of random size.

      Unless configured otherwise, the generated size will be between Keys.COLLECTION_MIN_SIZE and Keys.COLLECTION_MAX_SIZE, inclusive.

      To create a list of a specific size, use ofList(Class).

      Type Parameters:
      T - element type
      Parameters:
      elementType - class to generate as list elements
      Returns:
      API builder reference
      Since:
      3.0.1
    • createSet

      public static <T> Set<T> createSet(Class<T> elementType)
      Creates a Set of random size.

      Unless configured otherwise, the generated size will be between Keys.COLLECTION_MIN_SIZE and Keys.COLLECTION_MAX_SIZE, inclusive.

      To create a Set of a specific size, use ofSet(Class).

      Type Parameters:
      T - element type
      Parameters:
      elementType - class to generate as set elements
      Returns:
      API builder reference
      Since:
      3.0.1
    • createMap

      public static <K, V> Map<K,V> createMap(Class<K> keyType, Class<V> valueType)
      Creates a Map of random size.

      Unless configured otherwise, the generated size will be between Keys.MAP_MIN_SIZE and Keys.MAP_MAX_SIZE, inclusive.

      To create a Map of a specific size, use ofMap(Class, Class).

      Type Parameters:
      K - key type
      V - value type
      Parameters:
      keyType - class to generate as map keys
      valueType - class to generate as map values
      Returns:
      API builder reference
      Since:
      3.0.1
    • stream

      public static <T> Stream<T> stream(Class<T> type)
      Creates an infinite stream of instances of the specified class.

      Example:

      
       List<Person> persons = Instancio.stream(Person.class)
           .limit(5)
           .collect(Collectors.toList());
       
      Type Parameters:
      T - the type of object
      Parameters:
      type - to create
      Returns:
      an infinite stream of objects of the specified type
      Since:
      1.1.9
    • create

      public static <T> T create(TypeTokenSupplier<T> typeToken)
      Creates an object of type specified by the type token. This method can be used for creating instances of generic types.

      Example:

      
       Pair<UUID, Person> pair = Instancio.create(new TypeToken<Pair<UUID, Person>>(){});
       
      Type Parameters:
      T - the type of object
      Parameters:
      typeToken - specifying the type to create
      Returns:
      an object of the specified type
    • stream

      public static <T> Stream<T> stream(TypeTokenSupplier<T> typeToken)
      Creates an infinite stream of objects of type specified by the type token. This method can be used for creating streams of generic types.

      Example:

      
       List<Pair<Integer, String>> pairs = Instancio.stream(new TypeToken<Pair<Integer, String>>() {})
           .limit(5)
           .collect(Collectors.toList());
       
      Type Parameters:
      T - the type of object
      Parameters:
      typeToken - specifying the type to create
      Returns:
      an infinite stream of objects of the specified type
      Since:
      1.1.9
    • create

      public static <T> T create(Model<T> model)
      Creates an object populated using the given model. If the object needs to be customised, use the of(Model) method.

      For an example of how to create a model, see InstancioApi.toModel().

      Type Parameters:
      T - the type of object
      Parameters:
      model - a model that will be used as a template for creating the object
      Returns:
      an object created based on the model
      See Also:
    • stream

      public static <T> Stream<T> stream(Model<T> model)
      Creates an infinite stream of objects populated using the given model.

      For example, given the following model:

      
       Model<Person> model = Instancio.of(Person.class)
           .ignore(field(Person::getId))
           .generate(field(Person::dateOfBirth), gen -> gen.temporal().localDate().past())
           .toModel();
       

      you can create a stream of objects as follows:

      
       List<Person> persons = Instancio.stream(model)
           .limit(5)
           .collect(Collectors.toList());
       
      Type Parameters:
      T - the type of object
      Parameters:
      model - that will be used to generate the objects
      Returns:
      an infinite stream of objects created based on the model
      Since:
      2.4.0
      See Also:
    • of

      public static <T> InstancioClassApi<T> of(Class<T> type)
      Builder version of create(Class) that allows customisation of generated values.
      
       Person person = Instancio.of(Person.class)
           .generate(allInts(), gen -> gen.ints().min(1).max(99))
           .supply(all(Address.class), () -> new Address("742 Evergreen Terrace", "Springfield", "US"))
           .supply(field("pets"), () -> List.of(
                               new Pet(PetType.CAT, "Snowball"),
                               new Pet(PetType.DOG, "Santa's Little Helper")))
           .create();
       
      Type Parameters:
      T - the type of object
      Parameters:
      type - to create
      Returns:
      API builder reference
    • ofBlank

      @ExperimentalApi public static <T> InstancioClassApi<T> ofBlank(Class<T> type)
      Builder version of the createBlank(Class) method that allows customisation of generated values.

      For example, assuming the following POJO:

      
       class Person {
           String name;
           LocalDate dateOfBirth;
           List<Phone> phoneNumbers;
           Address address;
       }
       

      The snippet below will create a blank Person object with two initialised fields:

      
       Person person = Instancio.ofBlank(Person.class)
           .set(field(Address::getCountry), "Canada")
           .generate(field(Person::getDateOfBirth), gen -> gen.temporal().localDate().past())
           .create()
      
       // Sample output:
       // Person[
       //   name=null,
       //   dateOfBirth=1990-12-29,
       //   phoneNumbers=[]
       //   address=Address[street=null, city=null, country=Canada]
       //]
       
      Type Parameters:
      T - the type of object
      Parameters:
      type - the type of blank object to create
      Returns:
      API builder reference
      Since:
      4.7.0
      See Also:
    • of

      public static <T> InstancioApi<T> of(TypeTokenSupplier<T> typeToken)
      Builder version of create(TypeTokenSupplier) that allows customisation of generated values.
      
       List<Person> persons = Instancio.of(new TypeToken<List<Person>>(){})
           .generate(allInts(), gen -> gen.ints().min(1).max(99))
           .supply(all(Address.class), () -> new Address("742 Evergreen Terrace", "Springfield", "US"))
           .supply(field("pets"), () -> List.of(
                               new Pet(PetType.CAT, "Snowball"),
                               new Pet(PetType.DOG, "Santa's Little Helper")))
           .create();
       
      Type Parameters:
      T - the type of object
      Parameters:
      typeToken - specifying the type to create
      Returns:
      API builder reference
    • of

      public static <T> InstancioApi<T> of(Model<T> model)
      Builder version of create(Model) that allows overriding of generation parameters of an existing model.
      
       Model<Person> personModel = Instancio.of(Person.class)
           .generate(allInts(), gen -> gen.ints().min(1).max(99))
           .supply(all(Address.class), () -> new Address("742 Evergreen Terrace", "Springfield", "US"))
           .supply(field("pets"), () -> List.of(
                               new Pet(PetType.CAT, "Snowball"),
                               new Pet(PetType.DOG, "Santa's Little Helper")))
           .toModel();
      
       // Use the existing model and add/override generation parameters
       Person simpsonKid = Instancio.of(personModel)
           .generate(field("fullName"), gen -> gen.oneOf("Lisa Simpson", "Bart Simpson"))
           .create();
       
      Type Parameters:
      T - the type of object
      Parameters:
      model - specifying generation parameters of the object to create
      Returns:
      API builder reference
    • fill

      @ExperimentalApi public static <T> void fill(T object)
      Fills the fields of the given object with randomly generated values, preserving existing non-null and non-default values.

      For more details, including customisation options and usage constraints, refer to the ofObject(Object) method.

      Type Parameters:
      T - the type of the object
      Parameters:
      object - the object whose fields should be populated with random values.
      Since:
      5.3.0
      See Also:
    • ofObject

      @ExperimentalApi public static <T> InstancioObjectApi<T> ofObject(T object)
      A builder API for populating fields of the given object with randomly generated values.

      By default, only fields that are null or primitive fields with default values will be populated, while existing non-null and non-default primitive values will remain unchanged.

      For example, given the following class:

      
       class Person {
           private String name;
           private String email;
           private LocalDate dateOfBirth;
           // getters and setters
       }
       

      A Person instance can be populated as follows:

      
       // Given a person with some initialised fields
       Person person = new Person();
       person.setDateOfBirth(LocalDate.of(1980, 12, 31));
      
       // Populate the rest of the object
       Instancio.ofObject(person)
           .generate(field(Person::getEmail), gen -> gen.net().email())
           .fill();
      
       // Sample output:
       // Person[name=VCNSOU, email=fphna@mph.org, dateOfBirth=1980-12-31]
       
      • The name field which was null was populated with a random value.
      • The email field was generated using the specified email generator.
      • The dateOfBirth field retained the initialised value.

      Note that by default, Instancio uses the FillType.POPULATE_NULLS_AND_DEFAULT_PRIMITIVES when populating objects. The default fill type can be customised in two ways:

      For example, when using FillType.APPLY_SELECTORS, the object will be modified only via selectors:

      
       Person person = new Person();
       person.setDateOfBirth(LocalDate.of(1980, 12, 31));
      
       Instancio.ofObject(person)
           .withFillType(FillType.APPLY_SELECTORS)
           .generate(field(Person::getEmail), gen -> gen.net().email())
           .fill();
      
       // Sample output (note: the name field remains null):
       // Person[name=null, email=xnb@mfk4.org, dateOfBirth=1980-12-31]
       

      Limitations

      The input object must satisfy the following requirements:

      • Must not be a parameterized type except for Collection or Map
      • Must not be an empty collection or map

      Note: While this method can populate fields within elements of a collection, it does not:

      • Add new elements to the collection.
      • Replace null elements with non-null values.

      As a result, initialised collections will retain their original size unless overwritten with a new collection instance via a selector.

      Type Parameters:
      T - the type of the object
      Parameters:
      object - the object whose fields should be populated with random values
      Returns:
      API builder reference
      Since:
      5.3.0
      See Also:
    • ofCartesianProduct

      @ExperimentalApi public static <T> InstancioCartesianProductApi<T> ofCartesianProduct(Class<T> type)
      Generates the Cartesian product based on the values specified via the with() method. The Cartesian product is returned as a List in lexicographical order.

      Example:

      
       record Widget(String type, int num) {}
      
       List<Widget> results = Instancio.ofCartesianProduct(Widget.class)
           .with(field(Widget::type), "FOO", "BAR", "BAZ")
           .with(field(Widget::num), 1, 2, 3)
           .create();
       

      This will produce the following list of Widget objects:

       [Widget[type=FOO, num=1],
        Widget[type=FOO, num=2],
        Widget[type=FOO, num=3],
        Widget[type=BAR, num=1],
        Widget[type=BAR, num=2],
        Widget[type=BAR, num=3],
        Widget[type=BAZ, num=1],
        Widget[type=BAZ, num=2],
        Widget[type=BAZ, num=3]]
       
      Type Parameters:
      T - the type of object
      Parameters:
      type - to create
      Returns:
      API builder reference
      Since:
      4.0.0
      See Also:
    • ofCartesianProduct

      @ExperimentalApi public static <T> InstancioCartesianProductApi<T> ofCartesianProduct(TypeTokenSupplier<T> typeToken)
      Generates the Cartesian product based on the values specified via the with() method. The Cartesian product is returned as a List in lexicographical order.

      See ofCartesianProduct(Class) for an example.

      Type Parameters:
      T - the type of object
      Parameters:
      typeToken - specifying the type to create
      Returns:
      API builder reference
      Since:
      4.0.0
      See Also:
    • ofCartesianProduct

      @ExperimentalApi public static <T> InstancioCartesianProductApi<T> ofCartesianProduct(Model<T> model)
      Generates the Cartesian product based on the values specified via the with() method. The Cartesian product is returned as a List in lexicographical order.

      See ofCartesianProduct(Class) for an example.

      Type Parameters:
      T - the type of object
      Parameters:
      model - specifying generation parameters of the object to create
      Returns:
      API builder reference
      Since:
      4.0.0
      See Also:
    • ofList

      public static <T> InstancioCollectionsApi<List<T>> ofList(Class<T> elementType)
      Builder API for generating a List that allows customising generated values.
      Type Parameters:
      T - element type
      Parameters:
      elementType - class to generate as list elements
      Returns:
      API builder reference
      Since:
      2.0.0
    • ofList

      public static <T> InstancioCollectionsApi<List<T>> ofList(TypeTokenSupplier<T> elementTypeToken)
      Builder API for generating a List using a type token.
      Type Parameters:
      T - element type
      Parameters:
      elementTypeToken - specifying the element type
      Returns:
      API builder reference
      Since:
      2.16.0
    • ofList

      public static <T> InstancioCollectionsApi<List<T>> ofList(Model<T> elementModel)
      Builder API for generating a List using the specified model for list elements.
      Type Parameters:
      T - element type
      Parameters:
      elementModel - a model for creating list elements
      Returns:
      API builder reference
      Since:
      2.5.0
    • ofSet

      public static <T> InstancioCollectionsApi<Set<T>> ofSet(Class<T> elementType)
      Builder API for generating a Set that allows customisation of generated values.
      Type Parameters:
      T - element type
      Parameters:
      elementType - class to generate as set elements
      Returns:
      API builder reference
      Since:
      2.0.0
    • ofSet

      public static <T> InstancioCollectionsApi<Set<T>> ofSet(TypeTokenSupplier<T> elementTypeToken)
      Builder API for generating a Set using a type token.
      Type Parameters:
      T - element type
      Parameters:
      elementTypeToken - specifying the element type
      Returns:
      API builder reference
      Since:
      2.16.0
    • ofSet

      public static <T> InstancioCollectionsApi<Set<T>> ofSet(Model<T> elementModel)
      Builder API for generating a Set using the specified model for list elements.
      Type Parameters:
      T - element type
      Parameters:
      elementModel - a model for creating set elements
      Returns:
      API builder reference
      Since:
      2.5.0
    • ofMap

      public static <K, V> InstancioCollectionsApi<Map<K,V>> ofMap(Class<K> keyType, Class<V> valueType)
      Builder API for generating a Map that allowss customisation of generated values.
      Type Parameters:
      K - key type
      V - value type
      Parameters:
      keyType - class to generate as map keys
      valueType - class to generate as map values
      Returns:
      API builder reference
      Since:
      2.0.0
    • ofMap

      public static <K, V> InstancioCollectionsApi<Map<K,V>> ofMap(TypeTokenSupplier<K> keyTypeToken, TypeTokenSupplier<V> valueTypeToken)
      Builder API for generating a Map using type tokens.
      Type Parameters:
      K - key type
      V - value type
      Parameters:
      keyTypeToken - specifying the key type
      valueTypeToken - specifying the value type
      Returns:
      API builder reference
      Since:
      2.16.0
    • gen

      @ExperimentalApi public static InstancioGenApi gen()
      A shorthand API for generating simple value types, such as strings, numbers, dates, etc.

      This API supports generating a single value using the get() method:

      
       URL url = Instancio.gen().net().url().get();
      
       String randomChoice = Instancio.gen().oneOf("foo", "bar", "baz").get();
       

      as well as generating a list of values using the list(int size) method:

      
       List<LocalDate> pastDates = Instancio.gen().temporal().localDate().past().list(5);
      
       List<String> uuids = Instancio.gen().text().uuid().upperCase().withoutDashes().list(5);
       

      Additionally, the API can generate an infinite stream of values, for example a stream of strings in the "ABC-123" format:

      
       Stream<String> pastDates = Instancio.gen().text().pattern("#C#C#C-#d#d#d")
         .stream()
         .limit(100); // limit must be called to avoid an infinite loop
       
      Returns:
      API builder reference
      Since:
      5.0.0
    • createFeed

      @ExperimentalApi public static <F extends Feed> F createFeed(Class<F> type)
      Creates a feed of the specified type.
      Type Parameters:
      F - the type of feed
      Parameters:
      type - the class that defines a feed
      Returns:
      API builder reference
      Since:
      5.0.0
      See Also:
    • ofFeed

      @ExperimentalApi public static <F extends Feed> InstancioFeedApi<F> ofFeed(Class<F> type)
      Builder version of createFeed(Class) that allows customising the feed's properties.
      Type Parameters:
      F - the type of feed
      Parameters:
      type - the class that defines a feed
      Returns:
      API builder reference
      Since:
      5.0.0
      See Also: