Package org.instancio

Interface InstancioApi<T>

Type Parameters:
T - type to create
All Superinterfaces:
BaseApi<T>, LenientModeApi, SettingsApi, VerboseModeApi
All Known Subinterfaces:
InstancioClassApi<T>, InstancioCollectionsApi<C>

public interface InstancioApi<T> extends BaseApi<T>, SettingsApi, LenientModeApi, VerboseModeApi
Instancio API for generating instances of a class populated with random data.
Since:
1.0.1
  • Method Details

    • create

      T create()
      Creates a new instance of a class and populates it with data.

      Example:

      
       Person person = Instancio.of(Person.class)
           // snip...
           .create();
       

      The returned object will have all its fields populated with random data, including collection and array fields.

      Returns:
      a fully populated object
      Since:
      1.0.1
    • asResult

      Result<T> asResult()
      Returns a Result containing the created object and seed value used to generate its values. The seed value can be used to reproduce the same object again.

      Example:

      
       Result<Person> result = Instancio.of(Person.class)
           .set(field(Person::getName), "Homer Simpson")
           .asResult();
      
       Person person = result.get();
       long seed = result.getSeed();
       
      Returns:
      result containing the created object
      Since:
      1.5.1
    • as

      @ExperimentalApi default <R> R as(Function<T,R> function)
      A convenience method for mapping the result (as returned by the create() method) to another object using a function.

      For example, this method can be used to return the result as JSON or other formats:

      
       String json = Instancio.of(Person.class).as(json());
       

      where json() is a user-defined method implemented using the preferred library, e.g. using Jackson:

      
       public static <T> Function<T, String> json() {
           return result -> new ObjectMapper()
                   .writerWithDefaultPrettyPrinter()
                   .writeValueAsString(result);
       }
       
      Type Parameters:
      R - the type of object the result is mapped to
      Parameters:
      function - the function for mapping the result
      Returns:
      the object returned by applying the mapping function to the result
      Since:
      4.8.0
    • stream

      Stream<T> stream()
      Creates an infinite Stream of objects. Ensure limit() is called on the returned stream to prevent an infinite loop.

      Each object is generated separately when using this method. For instance, if a stateful generator like a sequence generator is used, the sequence will restart from one for each object:

      
       List<Person> persons = Instancio.of(Person.class)
           .generate(field(Person::getId), gen -> gen.longSeq())
           .stream()
           .limit(3)
           .collect(Collectors.toList());
      
       // Output:
       // [Person[id=1], Person[id=1], Person[id=1]]
       

      Compared to using ofList(), where the sequence is continuous:

      
       List<Person> persons = Instancio.ofList(Person.class)
           .size(3)
           .generate(field(Person::getId), gen -> gen.longSeq())
           .create();
      
       // Output:
       // [Person[id=1], Person[id=2], Person[id=3]]
       
      Returns:
      an infinite stream of object instances
      Since:
      1.1.9
    • toModel

      Model<T> toModel()
      Creates a model containing generation parameters for creating an object A model acts as a template for creating objects or other models.

      The example below illustrates how to create a reusable model with predefined attributes, which serves as a template for generating objects with base properties:

      
       Model<Person> simpsons = Instancio.of(Person.class)
           .set(field(Person::getLastName), "Simpson")
           .set(field(Address::getCity), "Springfield")
           .generate(field(Person::getAge), gen -> gen.ints().range(40, 50))
           .toModel();
      
       Person homer = Instancio.of(simpsons)
           .set(field(Person::getFirstName), "Homer")
           .set(all(Gender.class), Gender.MALE)
           .create();
      
       Person marge = Instancio.of(simpsons)
           .set(field(Person::getFirstName), "Marge")
           .set(all(Gender.class), Gender.FEMALE)
           .create();
       

      For more information, see:

      Returns:
      a model that can be used as a template for creating objects
      Since:
      1.0.1
      See Also:
    • ignore

      InstancioApi<T> ignore(TargetSelector selector)
      Specifies that a class or field should be ignored.

      Example:

      
       Person person = Instancio.of(Person.class)
           .ignore(field(Phone::getPhoneNumber))
           .ignore(allStrings())
           .create();
       

      will create a fully populated person, but will ignore the getPhoneNumber field, and all strings.

      Precedence

      This method has higher precedence than other API methods. Once a target is ignored, no other selectors will apply. For example, the following snippet will trigger an unused selector error because field(Phone::getNumber) is redundant:

      
       Person person = Instancio.of(Person.class)
           .ignore(all(Phone.class))
           .set(field(Phone::getNumber), "123-45-56")
           .create();
       

      Usage with Java records

      If ignore() targets one of the required arguments of a record constructor, then a default value for the ignored type will be generated.

      Example:

      
       record PersonRecord(String name, int age) {}
      
       PersonRecord person = Instancio.of(PersonRecord.class)
           .ignore(allInts())
           .ignore(allStrings())
           .create();
      
       // will produce: PersonRecord[name=null, age=0]
       
      Specified by:
      ignore in interface BaseApi<T>
      Parameters:
      selector - for fields and/or classes this method should be applied to
      Returns:
      API builder reference
      Since:
      1.0.1
    • withNullable

      InstancioApi<T> withNullable(TargetSelector selector)
      Specifies that a field or class is nullable. By default, Instancio assigns non-null values to fields. If marked as nullable, Instancio will generate either a null or non-null value.

      Example:

      
       Person person = Instancio.of(Person.class)
           .withNullable(allStrings())
           .withNullable(field(Person::getAddress))
           .withNullable(fields().named("lastModified"))
           .create();
       
      Note: a type marked as nullable using this method is only nullable when declared as a field, but not as a collection element, or map key/value. For example, withNullable(allStrings()) will not generate nulls in a List<String>.
      Specified by:
      withNullable in interface BaseApi<T>
      Parameters:
      selector - for fields and/or classes this method should be applied to
      Returns:
      API builder reference
      Since:
      1.0.1
    • set

      <V> InstancioApi<T> set(TargetSelector selector, V value)
      Sets a value to matching selector targets.

      Example: if Person class contains a List<Phone>, the following snippet will set all the country code of all phone instances to "+1".

      
       Person person = Instancio.of(Person.class)
           .set(field(Phone::getCountryCode), "+1")
           .create();
       

      Note: Instancio will not

      • populate or modify objects supplied by this method
      • apply other set(), supply(), or generate()} methods with matching selectors to the supplied object
      • invoke onComplete() callbacks on supplied instances
      Specified by:
      set in interface BaseApi<T>
      Type Parameters:
      V - type of the value
      Parameters:
      selector - for fields and/or classes this method should be applied to
      value - value to set
      Returns:
      API builder reference
      Since:
      1.2.3
      See Also:
    • setModel

      @ExperimentalApi <V> InstancioApi<T> setModel(TargetSelector selector, Model<V> model)
      Applies given model to the specified selector.

      For example, given the following classes and Model:

      
       record Foo(String value) {}
       record Container(Foo fooA, Foo fooB) {}
      
       Model<Foo> fooModel = Instancio.of(Foo.class)
           .set(field(Foo::value), "foo")
           .toModel();
       

      The model can be applied to a specific Foo field declared by the Container:

      
       Container container = Instancio.of(Container.class)
           .setModel(field(Container::fooA), fooModel)
           .create();
       

      Alternatively, to apply the model to all instances of Foo:

      
       Container container = Instancio.of(Container.class)
           .setModel(all(Foo.class), fooModel)
           .create();
       

      Note: the following properties of the supplied model are not applied to the target object:

      • Settings
      • lenient() mode
      • custom seed value

      See the user guide for further details.

      Specified by:
      setModel in interface BaseApi<T>
      Type Parameters:
      V - the type of object this model represents
      Parameters:
      selector - to which the model will be applied to
      model - to apply to the given selector's target
      Returns:
      API builder reference
      Since:
      4.4.0
    • supply

      <V> InstancioApi<T> supply(TargetSelector selector, Supplier<V> supplier)
      Supplies an object using a Supplier.

      Example:

      
       Person person = Instancio.of(Person.class)
           .supply(all(LocalDateTime.class), () -> LocalDateTime.now())
           .supply(field(Address::getPhoneNumbers), () -> List.of(
               new PhoneNumber("+1", "123-45-67"),
               new PhoneNumber("+1", "345-67-89")))
           .create();
       

      Note: Instancio will not

      • populate or modify objects supplied by this method
      • apply other set(), supply(), or generate()} methods with matching selectors to the supplied object
      • invoke onComplete() callbacks on supplied instances

      If you require the supplied object to be populated and/or selectors to be applied, use the BaseApi.supply(TargetSelector, Generator) method instead.

      Specified by:
      supply in interface BaseApi<T>
      Type Parameters:
      V - type of the supplied value
      Parameters:
      selector - for fields and/or classes this method should be applied to
      supplier - providing the value for given selector
      Returns:
      API builder reference
      Since:
      1.0.1
      See Also:
    • supply

      <V> InstancioApi<T> supply(TargetSelector selector, Generator<V> generator)
      Supplies an object using a Generator to matching selector targets. By default, Instancio will populate uninitialised fields of the supplied object. This includes fields with null or default primitive values.

      This method supports the following use cases.

      Generate random objects

      This method provides an instance of Random that can be used to randomise generated objects. For example, if Instancio did not support creation of java.time.Year, it could be generated as follows:

      
       List<Year> years = Instancio.ofList(Year.class)
           .supply(all(Year.class), random -> Year.of(random.intRange(1900, 2000)))
           .create();
       

      Provide a partially initialised instance

      In some cases, an object may need to be created in a certain state or instantiated using a specific constructor to be in a valid state. A partially initialised instance can be supplied using this method, and Instancio will populate remaining fields that are null:

      
       Person person = Instancio.of(Person.class)
           .supply(field(Person::getAddress), random -> new Address("Springfield", "USA"))
           .create();
       

      This behaviour is controlled by the AfterGenerate hint specified by Generator.hints(). Refer to the Generator.hints() Javadoc for details, or Custom Generators section of the user guide.

      Specified by:
      supply in interface BaseApi<T>
      Type Parameters:
      V - type of the value to generate
      Parameters:
      selector - for fields and/or classes this method should be applied to
      generator - that will provide the values
      Returns:
      API builder reference
      Since:
      1.0.1
      See Also:
    • generate

      <V> InstancioApi<T> generate(TargetSelector selector, GeneratorSpecProvider<V> gen)
      Customises values using built-in generators provided by the gen parameter, of type Generators.

      Example:

      
       Person person = Instancio.of(Person.class)
           .generate(field(Person::getAge), gen -> gen.ints().range(18, 100))
           .generate(all(LocalDate.class), gen -> gen.temporal().localDate().past())
           .generate(field(Address::getPhoneNumbers), gen -> gen.collection().size(5))
           .generate(field(Address::getCity), gen -> gen.oneOf("Burnaby", "Vancouver", "Richmond"))
           .create();
       
      Specified by:
      generate in interface BaseApi<T>
      Type Parameters:
      V - type of object to generate
      Parameters:
      selector - for fields and/or classes this method should be applied to
      gen - provider of customisable built-in generators (also known as specs)
      Returns:
      API builder reference
      Since:
      2.2.0
      See Also:
    • generate

      @ExperimentalApi <V> InstancioApi<T> generate(TargetSelector selector, GeneratorSpec<V> spec)
      Customises values using arbitrary generator specs.

      Example:

      
       Person person = Instancio.of(Person.class)
           .generate(field(Person::getAge), Instancio.ints().range(18, 100))
           .generate(all(LocalDate.class),  Instancio.temporal().localDate().past())
           .generate(field(Phone::getNumber),  MyCustomGenerators.phones().northAmerican())
           .create();
       
      Specified by:
      generate in interface BaseApi<T>
      Type Parameters:
      V - type of object to generate
      Parameters:
      selector - for fields and/or classes this method should be applied to
      spec - generator spec
      Returns:
      API builder reference
      Since:
      2.6.0
      See Also:
    • onComplete

      <V> InstancioApi<T> onComplete(TargetSelector selector, OnCompleteCallback<V> callback)
      A callback that gets invoked after an object has been fully populated.

      Example:

      
       // Sets countryCode field on all instances of Phone to the specified value
       Person person = Instancio.of(Person.class)
           .onComplete(all(Phone.class), (Phone phone) -> phone.setCountryCode("+1"))
           .create();
       

      Note: callbacks are never invoked on objects provided using:

      
       Person person = Instancio.of(Person.class)
           .set(field(Phone::getCountryCode), "+1")
           .onComplete(field(Phone::getCountryCode), ...) // will not be invoked!
           .create();
       
      Specified by:
      onComplete in interface BaseApi<T>
      Type Parameters:
      V - type of object handled by the callback
      Parameters:
      selector - for fields and/or classes this method should be applied to
      callback - to invoke after object has been populated
      Returns:
      API builder reference
      Since:
      1.0.4
    • filter

      @ExperimentalApi <V> InstancioApi<T> filter(TargetSelector selector, FilterPredicate<V> predicate)
      Filters generated values using given predicate. If a value is rejected, a new value will be generated, which will also be tested against the predicate. If no value is accepted after Keys.MAX_GENERATION_ATTEMPTS, an exception will be thrown.

      A simple example is to generate a list of even numbers:

      
       List<Integer> evenNumbers = Instancio.ofList(Integer.class)
           .filter(allInts(), (Integer i) -> i % 2 == 0)
           .create();
       

      Note that customising objects using this method is less efficient than BaseApi.generate(TargetSelector, GeneratorSpecProvider). The latter should be preferred where possible.

      Specified by:
      filter in interface BaseApi<T>
      Type Parameters:
      V - the type of object the predicate is evaluated against
      Parameters:
      selector - for fields and/or classes this method should be applied to
      predicate - that must be satisfied by the generated value
      Returns:
      API builder reference
      Since:
      4.6.0
      See Also:
    • setBlank

      Specifies that a blank object should be generated for the selected target.

      A blank object has the following properties:

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

      Example:

      
       Person person = Instancio.of(Person.class)
           .setBlank(field(Person::getAddress))
           .create();
      
       // Output:
       // Person[
       //   name="GNQTXA",
       //   dateOfBirth=1988-04-09,
       //   address=Address[street=null, city=null, country=null] // blank Address
       //]
       
      Specified by:
      setBlank in interface BaseApi<T>
      Parameters:
      selector - for fields and/or classes this method should be applied to
      Returns:
      API builder reference
      Since:
      4.7.0
      See Also:
    • subtype

      InstancioApi<T> subtype(TargetSelector selector, Class<?> subtype)
      Maps target field or class to the given subtype. This can be used in the following cases:
      1. to specify an implementation for interfaces or abstract classes
      2. to override default implementations used by Instancio
      Specify an implementation for an abstract type

      When Instancio encounters an interface or an abstract type it is not aware of (for example, that is not part of the JDK), it will not be able to instantiate it. This method can be used to specify an implementation to use in such cases. For example:

      
       WidgetContainer container = Instancio.of(WidgetContainer.class)
           .subtype(all(AbstractWidget.class), ConcreteWidget.class)
           .create();
       

      Override default implementations

      By default, Instancio uses certain defaults for collection classes, for example ArrayList for List. If an alternative implementation is required, this method allows to specify it:

      
       Person person = Instancio.of(Person.class)
           .subtype(all(List.class), LinkedList.class)
           .create();
       

      will use the LinkedList implementation for all Lists.

      Specified by:
      subtype in interface BaseApi<T>
      Parameters:
      selector - for fields and/or classes this method should be applied to
      subtype - to map the selector to
      Returns:
      API builder reference
      Since:
      1.4.0
    • assign

      @ExperimentalApi InstancioApi<T> assign(Assignment... assignments)
      Generates values based on given assignments. An Assignment can be created using one of the builder patterns provided by the Assign class.
      • Assign.valueOf(originSelector).to(destinationSelector)
      • Assign.given(originSelector).satisfies(predicate).set(destinationSelector, value)
      • Assign.given(originSelector, destinationSelector).set(predicate, value)

      For example, the following snippet uses Assign.given(TargetSelector, TargetSelector) to create an assignment that sets Phone.countryCode based on the value of the Address.country field:

      
       Assignment assignment = Assign.given(field(Address::getCountry), field(Phone::getCountryCode))
           .set(When.isIn("Canada", "USA"), "+1")
           .set(When.is("Italy"), "+39")
           .set(When.is("Poland"), "+48")
           .set(When.is("Germany"), "+49");
      
       Person person = Instancio.of(Person.class)
           .generate(field(Address::getCountry), gen -> gen.oneOf("Canada", "USA", "Italy", "Poland", "Germany"))
           .assign(assignment)
           .create();
       

      The above API allows specifying different values for a given origin/destination pair. An alternative for creating a conditional is provided by Assign.given(TargetSelector). This method allows specifying different destination selectors for a given origin:

      
       Assignment shippedOrderAssignment = Assign.given(Order::getStatus)
           .is(OrderStatus.SHIPPED)
           .supply(field(Order::getDeliveryDueDate), () -> LocalDate.now().plusDays(2));
      
       Assignment cancelledOrderAssignment = Assign.given(Order::getStatus)
            .is(OrderStatus.CANCELLED)
            .set(field(Order::getCancellationReason), "Shipping delays")
            .generate(field(Order::getCancellationDate), gen -> gen.temporal().instant().past());
      
       List<Order> orders = Instancio.ofList(Order.class)
           .generate(all(OrderStatus.class), gen -> gen.oneOf(OrderStatus.SHIPPED, OrderStatus.CANCELLED))
           .assign(shippedOrderAssignment, cancelledOrderAssignment)
           .create();
       

      Limitations of assignments

      Using assignments has a few limitations to be aware of.

      • The origin selector must match a single target. It must not be a SelectorGroup created via Select.all(GroupableSelector...) or primitive/wrapper selector, such as Select.allInts()
      • An assignment where the origin selector's target is within a collection element must have a destination selector within the same collection element.
      • Circular assignments will produce an error.
      Specified by:
      assign in interface BaseApi<T>
      Parameters:
      assignments - one or more assignment expressions for setting values
      Returns:
      API builder reference
      Since:
      3.0.0
      See Also:
    • withMaxDepth

      InstancioApi<T> withMaxDepth(int maxDepth)
      Specifies the maximum depth for populating an object. The root object is at depth zero. Children of the root object are at depth 1, grandchildren at depth 2, and so on.

      Instancio will populate values up to the maximum depth. Beyond that, values will be null unless the maximum depth is set to a higher value.

      The default maximum depth is defined by Keys.MAX_DEPTH.

      Note: this method is a shorthand for:

      
       int maxDepth = 5;
       Person person = Instancio.of(Person.class)
           .withSettings(Settings.create().set(Keys.MAX_DEPTH, maxDepth))
           .create();
       

      If the maximum depth is specified using Settings and this method, then this method takes precedence.

      Specified by:
      withMaxDepth in interface BaseApi<T>
      Parameters:
      maxDepth - the maximum depth, must not be negative
      Returns:
      API builder reference
      Since:
      2.9.0
    • withSetting

      <V> InstancioApi<T> withSetting(SettingKey<V> key, V value)
      Overrides the setting for the given key with the specified value.
      Specified by:
      withSetting in interface SettingsApi
      Type Parameters:
      V - the setting value type
      Parameters:
      key - the setting key to override
      value - the setting value
      Returns:
      API builder reference
      Since:
      4.3.1
      See Also:
    • withSettings

      InstancioApi<T> withSettings(Settings settings)
      Merges the specified Settings with the current settings, allowing for the addition and update of settings.

      Use this method to apply custom settings to override the default ones. The provided settings will be combined with the existing settings, updating any overlapping values and adding any new ones.

      Specified by:
      withSettings in interface SettingsApi
      Parameters:
      settings - the custom settings to merge with the current settings
      Returns:
      API builder reference
      Since:
      1.0.1
      See Also:
    • withSeed

      InstancioApi<T> withSeed(long seed)
      Sets the seed value for the random number generator. If the seed is not specified, a random seed will be used. Specifying the seed is useful for reproducing test results. By specifying the seed value, the same random data will be generated again.

      Example:

      
       // Generates a different UUID each time
       UUID result = Instancio.create(UUID.class);
      
       // Generates the same UUID each time
       UUID result = Instancio.of(UUID.class)
           .withSeed(1234)
           .create();
       
      Specified by:
      withSeed in interface BaseApi<T>
      Parameters:
      seed - for the random number generator
      Returns:
      API builder reference
      Since:
      1.0.1
    • lenient

      InstancioApi<T> lenient()
      Disables strict mode in which unused selectors trigger an error. In lenient mode unused selectors are simply ignored.

      This method is a shorthand for:

      
       Example example = Instancio.of(Example.class)
           .withSetting(Keys.MODE, Mode.LENIENT)
           .create();
       
      Specified by:
      lenient in interface LenientModeApi
      Returns:
      API builder reference
      Since:
      1.4.1
    • verbose

      Outputs debug information to System.out. This includes:
      • current Settings
      • node hierarchy, including the type and depth of each node
      • seed used to create the object

      Warning: this method has a significant performance impact. It is recommended to remove the call to verbose() after troubleshooting is complete.

      Specified by:
      verbose in interface VerboseModeApi
      Returns:
      API builder reference
      Since:
      3.0.0
    • applyFeed

      @ExperimentalApi InstancioApi<T> applyFeed(TargetSelector selector, Feed feed)
      Applies the provided feed to the specified selector. The selector targets must be POJOs or Java records. Properties from the feed will be automatically mapped to the selected objects.

      For example, we can generate instances of the following record:

      
       record Person(String firstName, String lastName, String fullName,
                     int age, String username, String email) {}
       

      using data from a CSV file (formatted for readability):

       firstName, lastName, age, username
       John,      Doe,      24,  john_doe
       Alice,     Smith,    55,  alice_s
       # more entries...
       

      by defining the following feed:

      
       @Feed.Source(resource = "persons.csv")
       interface PersonFeed extends Feed {
      
           @TemplateSpec("${firstName} ${lastName}")
           FeedSpec<String> fullName();
      
           @GeneratedSpec(CustomEmailGenerator.class)
           FeedSpec<String> email();
       }
       

      and applying the feed using the all(Person.class) selector:

      
       Feed personFeed = Instancio.createFeed(PersonFeed.class);
      
       List<Person> persons = Instancio.ofList(Person.class)
           .applyFeed(all(Person.class), personFeed)
           .create();
       

      Data from the CSV will be mapped to Person fields by matching field names to property names in the data file.

      • Note that PersonFeed does not need to declare firstName() and lastName() methods (they are mapped automatically).
      • fullName() and email() can also be mapped to the Person object, even though these are generated and not present in the data file.
      Specified by:
      applyFeed in interface BaseApi<T>
      Parameters:
      selector - for fields and/or classes this method should be applied to
      feed - the feed to apply to the selector
      Returns:
      API builder reference
      Since:
      5.0.0
      See Also:
    • applyFeed

      @ExperimentalApi InstancioApi<T> applyFeed(TargetSelector selector, FeedProvider provider)
      Creates a feed and applies it to the specified selector. The selector's target must be a POJO or a Java record. Properties from the feed will be automatically mapped to the selected object.

      For example, given the following CSV file (formatted for readability):

       firstName, lastName, age, username
       John,      Doe,      24,  john_doe
       Alice,     Smith,    55,  alice_s
       # more entries...
       

      and a record with matching properties:

      
       class Person(String firstName, String lastName, int age, String username) {}
       

      a feed can be applied as follows:

      
       List<Person> persons = Instancio.ofList(Person.class)
           .applyFeed(all(Person.class), feed -> feed.ofResource("data/persons.csv"))
           .create();
      
       // Output:
       // [Person[firstName=John, lastName=Doe, age=24, username=john_doe],
       //  Person[firstName=Alice, lastName=Smith, age=55, username=alice_s]]
       
      Specified by:
      applyFeed in interface BaseApi<T>
      Parameters:
      selector - for fields and/or classes this method should be applied to
      provider - the provider API for specifying feed configuration
      Returns:
      API builder reference
      Since:
      5.0.0
      See Also:
    • withUnique

      Specifies that the given selector's target(s) should have unique values.

      Example:

      
       record Data(int foo, int bar) {}
      
       List<Data> results = Instancio.ofList(Data.class)
           .size(100)
           .withUnique(field(Data::foo))
           .create();
       

      The above snippet generates a list of Data instances with unique foo values. Note that values will be unique across all targets that match the selector. For instance, the following usages:

      • withUnique(allInts())
      • withUnique(all(field(Data::foo), field(Data::bar))

      would result in unique values for foo and bar with no overlap (i.e. foo and bar are disjoint). To generate unique values per field (with potential overlap), the withUnique() method must be specified per field:

      
       List<Data> results = Instancio.ofList(Data.class)
           .size(100)
           .withUnique(field(Data::foo)) // e.g. { 601, 42, 573, ...}
           .withUnique(field(Data::bar)) // e.g. { 888, 251, 42, ...}
           .create();
       

      If it is impossible to generate a sufficient number of unique values after a certain number of attempts, an exception will be thrown:

      
       List<Boolean> results = Instancio.ofList(Boolean.class)
           .size(10) // will fail as it's impossible to generate 10 unique booleans
           .withUnique(allBooleans())
           .create();
       
      Specified by:
      withUnique in interface BaseApi<T>
      Parameters:
      selector - for fields and/or classes this method should be applied to
      Returns:
      API builder reference
      Since:
      4.8.0