Java Reference
In-Depth Information
Suppose that your application contained a list of an arbitrary type, and you wanted
to apply a method to each of the objects in that list. Method references can be used in
this scenario, given the object contains methods that are candidates for use via referen-
ce. In the following example, the Arrays.sort() method is applied to a list of int
values, and a method reference is used to apply the Integer compare() method
to the elements within the list. Thus, the resulting list will be sorted, and the method
reference automatically passes the int arguments and returns the int comparison.
Integer[] ints = {3,5,7,8,51,33,1};
Arrays.sort(ints, Integer::compare);
The last type of method reference can be utilized for referencing the constructor of
an object. This type of method reference can be especially useful when creating new
objects via a factory. Let's take a look at an example. Suppose that the Player object
contained the following constructor:
public Player(String position, int status, String first,
String last){
this.position = position;
this.status = status;
this.firstName = first;
this.lastName = last;
}
You are interested in generating Player objects on-the-fly, using a factory pattern.
The following code demonstrates an example of a functional interface containing a
single abstract method named createPlayer() , which accepts the same argument
list as the constructor for the Player object.
public interface PlayerFactory {
Player createPlayer(String position,
int status,
String firstName,
String lastName);
}
The factory can now be created from a lambda expression, and then called upon to
create new objects. The following lines of code demonstrate:
Search WWH ::




Custom Search