Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 Supplier with arguments in the constructor

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")) 
like image 265
cahen Avatar asked Jul 06 '15 17:07

cahen


People also ask

Can constructor have arguments in Java?

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.

Can a constructor accept arguments?

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.

How arguments are passed to the constructor?

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.

How do you pass a constructor as an argument in Java?

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.


1 Answers

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.

like image 74
Brian Goetz Avatar answered Sep 21 '22 17:09

Brian Goetz