I was reading about Java 8 features, which lead me to this article and I was wondering about the actual uses of constructor reference, I mean why not just use new Obj
?
P.S, I tried googling, but I failed to find something meaningful, if someone has a code example, link or tut it will be great
First of all, you should understand that constructor references are just a special form of method references. The point about method references is that they do not invoke the referenced method but provide a way to define a function which will invoke the method when being evaluated.
The linked article’s examples might not look that useful but that’s the general problem of short self-contained example code. It’s just the same as with the “hello world” program. It’s not more useful than typing the text “hello world” directly into the console but it’s not meant to be anyway. It’s purpose is to demonstrate the programming language.
As assylias has shown, there are use cases involving already existing functional interface
s using the JFC API.
Regarding the usefulness of a custom functional interface that’ll be used together with a constructor reference, you have to think about the reason to use (functional) interface
in general: abstraction.
Since the purpose of an interface
is to abstract the underlying operation, the use cases are the places where you do not want to perform an unconditional new SomeType(…)
operation.
So one example is the commonly known Factory pattern where you define an interface
to construct an object and implementing the factory via constructor reference is only one option out of the infinite possibilities.
Another important point are all kinds of Generic methods where the possibility to construct instances of the type, that is not known due to type erasure, is needed. They can be implemented via a function which is passed as parameter and whether one of the existing functional interface
s fits or a custom one is needed simply depends on the required number and types of parameters.
It's useful when you need to provide a constructor as a supplier or a function. Examples:
List<String> filtered = stringList.stream()
.filter(s -> !s.isEmpty())
.collect(Collectors.toCollection(ArrayList::new)); //() -> new ArrayList<> ()
Map<String, BigDecimal> numbersMap = new HashMap<>();
numbersMap.computeIfAbsent("2", BigDecimal::new); // s -> new BigDecimal(s)
someStream.toArray(Object[]::new); // i -> new Object[i]
etc.
来源:https://stackoverflow.com/questions/29386441/what-are-the-uses-of-constructor-reference-in-java-8