Java Reference
In-Depth Information
AutoCloseable
reference variable
autoCloseable
is created inside the
try
statement, so its
close-like method will be called when the body completes. In this example, we are in a static
main
method wherein we have a reference
rnd2
to an instance of the class, so we use this in
referring to the
AutoCloseable
-compatible method.
Example 9-3. ReferencesDemo2.java
public
public class
class
ReferencesDemo2
ReferencesDemo2
{
void
void
cloz
() {
System
.
out
.
println
(
"Stand-in close() method called"
);
}
public
public static
static
void
void
main
(
String
[]
args
)
throws
throws
Exception
{
ReferencesDemo2 rd2
=
new
new
ReferencesDemo2
();
// Use a method reference to assign the AutoCloseable interface
// variable "ac" to the matching method signature "c" (obviously
// short for close, but just to she the method name isn't what matters).
try
try
(
AutoCloseable autoCloseable
=
rd2:
:
cloz
) {
System
.
out
.
println
(
"Some action happening here."
);
}
}
}
The output is as follows:
Some action happening here.
Stand-in close() method called
It is, of course, possible to use this with your own functional interfaces, defined as in
Creat-
ing Your Own Functional Interfaces
.
You're also probably at least vaguely aware that any
normal Java object reference can be passed to
System.out.println()
and you'll get some
description of the referenced object.
Example 9-4
explores these two themes. We define a
functional interface imaginatively known as
FunInterface
with a method with a bunch of
arguments (merely to avoid it being mistaken for any existing functional interface). The
method name is
process
, but as you now know the name is not important; our implementa-
tion method goes by the name
work
. The
work
method is static, so we could not state that the
class
implements FunInterface
(even if the method names were the same; a static method
may not hide an inherited instance method), but we can nonetheless create a lambda referen-