Java Reference
In-Depth Information
Yuck! That's horrible! Although it's only three lines, it's three opaque lines—we all remember
saying “Do I really have to do it this way?” on first encounter. You already have a method
isHidden that you could use. Why do you have to wrap it up in a verbose FileFilter class and
then instantiate it? Because that's what you had to do prior to Java 8!
Now, in Java 8 you can rewrite that code as follows:
File[] hiddenFiles = new File(".").listFiles(File::isHidden);
Wow! Isn't that cool? You already have the function isHidden available, so you just pass it to the
listFiles method using the Java 8 method reference :: syntax (meaning “use this method as a
value”); note that we've also slipped into using the word function for methods. We'll explain
later how the mechanics work. One advantage is that your code now reads closer to the problem
statement. Here's a taste of what's coming: methods are no longer second-class values.
Analogously to using an object reference when you pass an object around (and object references
are created by new), in Java 8 when you write File::isHidden you create a method reference,
which can similarly be passed around. This concept is discussed in detail in chapter 3 . Given
that methods contain code (the executable body of a method), then using method references
enables passing code around as in figure 1.3 . Figure 1.4 illustrates the concept. You'll also see a
concrete example (selecting apples from an inventory) in the next section.
 
Search WWH ::




Custom Search