Class ApiImpl<T>

java.lang.Object
org.instancio.internal.ApiImpl<T>
All Implemented Interfaces:
InstancioApi<T>
Direct Known Subclasses:
OfClassApiImpl

public class ApiImpl<T> extends Object implements InstancioApi<T>
  • Constructor Details

  • Method Details

    • addTypeParameters

      protected void addTypeParameters(Class<?>... type)
    • ignore

      public InstancioApi<T> ignore(TargetSelector selector)
      Description copied from interface: InstancioApi
      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 InstancioApi<T>
      Parameters:
      selector - for fields and/or classes this method should be applied to
      Returns:
      API builder reference
    • generate

      public <V> InstancioApi<T> generate(TargetSelector selector, GeneratorSpecProvider<V> gen)
      Description copied from interface: InstancioApi
      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 InstancioApi<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
      See Also:
    • generate

      public <V> InstancioApi<T> generate(TargetSelector selector, GeneratorSpec<V> spec)
      Description copied from interface: InstancioApi
      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 InstancioApi<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
      See Also:
    • onComplete

      public <V> InstancioApi<T> onComplete(TargetSelector selector, OnCompleteCallback<V> callback)
      Description copied from interface: InstancioApi
      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();
       
      Specified by:
      onComplete in interface InstancioApi<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
    • set

      public <V> InstancioApi<T> set(TargetSelector selector, V value)
      Description copied from interface: InstancioApi
      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();
       
      Specified by:
      set in interface InstancioApi<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
      See Also:
    • supply

      public <V> InstancioApi<T> supply(TargetSelector selector, Generator<V> generator)
      Description copied from interface: InstancioApi
      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 InstancioApi<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
      See Also:
    • supply

      public <V> InstancioApi<T> supply(TargetSelector selector, Supplier<V> supplier)
      Description copied from interface: InstancioApi
      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

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

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

      public InstancioApi<T> subtype(TargetSelector selector, Class<?> subtype)
      Description copied from interface: InstancioApi
      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 InstancioApi<T>
      Parameters:
      selector - for fields and/or classes this method should be applied to
      subtype - to map the selector to
      Returns:
      API builder reference
    • withSeed

      public InstancioApi<T> withSeed(long seed)
      Description copied from interface: InstancioApi
      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 InstancioApi<T>
      Parameters:
      seed - for the random number generator
      Returns:
      API builder reference
    • withNullable

      public InstancioApi<T> withNullable(TargetSelector selector)
      Description copied from interface: InstancioApi
      Specifies that a field or class is nullable. By default, Instancio assigns non-null values. 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();
       
      Specified by:
      withNullable in interface InstancioApi<T>
      Parameters:
      selector - for fields and/or classes this method should be applied to
      Returns:
      API builder reference
    • withSettings

      public InstancioApi<T> withSettings(Settings settings)
      Description copied from interface: InstancioApi
      Override default Settings for generating values. The Settings class supports various parameters, such as collection sizes, string lengths, numeric ranges, and so on. For a list of overridable settings, refer to the Keys class.
      Specified by:
      withSettings in interface InstancioApi<T>
      Parameters:
      settings - to use
      Returns:
      API builder reference
      See Also:
    • lenient

      public InstancioApi<T> lenient()
      Description copied from interface: InstancioApi
      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)
               .withSettings(Settings.create().set(Keys.MODE, Mode.LENIENT))
               .create();
       
      Specified by:
      lenient in interface InstancioApi<T>
      Returns:
      API builder reference
    • toModel

      public Model<T> toModel()
      Description copied from interface: InstancioApi
      Creates a model containing all the information for populating a class.

      The model can be useful when class population needs to be customised and the customisations need to be re-used in different parts of the code.

      Example:

      
         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();
       
      Specified by:
      toModel in interface InstancioApi<T>
      Returns:
      a model that can be used as a template for creating objects
    • create

      public T create()
      Description copied from interface: InstancioApi
      Creates a new instance of a class and populates it with data.

      Example:

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

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

      Specified by:
      create in interface InstancioApi<T>
      Returns:
      a fully populated object
    • asResult

      public Result<T> asResult()
      Description copied from interface: InstancioApi
      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.
      Specified by:
      asResult in interface InstancioApi<T>
      Returns:
      result containing the created object
    • stream

      public Stream<T> stream()
      Description copied from interface: InstancioApi
      Creates an infinite stream of distinct, fully populated objects.

      Example:

      
           List<Person> persons = Instancio.of(Person.class)
               .stream()
               .limit(5)
               .collect(Collectors.toList());
       
      Specified by:
      stream in interface InstancioApi<T>
      Returns:
      an infinite stream of distinct, populated objects