Why do suppliers only support no-arg constructors?
If the default constructor is present, I can do this:
create(Foo::new)
But if the only constructor takes a String, I have to do this:
create(() -> new Foo("hello"))
A Constructor with arguments(or you can say parameters) is known as Parameterized constructor. As we discussed in the Java Constructor tutorial that a constructor is a special type of method that initializes the newly created object.
Parameterized Constructor – A constructor is called Parameterized Constructor when it accepts a specific number of parameters. To initialize data members of a class with distinct values.
Arguments are passed by value. When invoked, a method or a constructor receives the value of the variable passed in. When the argument is of primitive type, "pass by value" means that the method cannot change its value.
Constructors can be passed as arugments to methods using a method reference, somewhat like a function pointer in C++. This can be a Function type with one argument or a BiFunction type with two arguments, either way its a lambda returning a class of the type it constructs.
But, a 1-arg constructor for T
that takes a String
is compatible with Function<String,T>
:
Function<String, Foo> fooSupplier = Foo::new;
Which constructor is selected is treated as an overload selection problem, based on the shape of the target type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With