javalambdajava-17functional-interface

Java: Creating a Supplier for a new instance of an Object from an instantiated Object


I want to create a Java Supplier from an existing instantiated Java object. Something like this would do:

CustomObject customObject = new CustomObject();
Supplier<CustomObject> newInstanceSupplier = Supplier.of(customObject)

This syntax for Supplier however does not exist for Java and I am wondering whether there is a convenient solution to this one.

I know I could easily create a supplier like this:

Supplier<CustomObject> supplier = ()-> new CustomObject()

or

Supplier<CustomObject> supplier = CustomObject::new

However, in my use-case, I want to take the Supplier from an existing custom object to allow for abstraction.

Is there a convenient way to do so?

This question tackles a slightly different approach.


Solution

  • Suppliers are not created that way. There is no static method Supplier#of(...) in the standard JDK.

    If you want to create a Supplier supplying a previously created instance, do this:

    CustomObject customObject = new CustomObject();
    Supplier<CustomObject> supplier = () -> customObject;
    

    Though doing this, you lose the benefits of lazy instantiation as the instance becomes always instantiated before and regardless of whether the supplier is called or not.

    Finally, remember the instance customObject must be marked as final or stay "effectively final", i.e. you can't reassign to it anything else.