Java Reference
In-Depth Information
▪ You can even reference “an Instance Method of an Arbitrary Object of a Particular
Type.”
The new syntax consists of an object or class name, two colons, and the name of a method
that can be invoked in the context of the object or class name (as per the usual rules of Java,
a class name can refer to static methods and an instance can refer to an instance method). To
refer to a constructor as the method, you can use new —for example, MyClass::new . The ref-
erence creates a lambda that can be invoked, stored in a variable of a functional interface
type, and so on.
In Example 9-2 , we create a Runnable reference that holds, not the usual run method, but a
method with the same type and arguments but with the name walk . Note the use of this as
the object part of the method reference. We then pass this Runnable into a Thread construct-
or and start the thread, with the result that walk is invoked where run would normally be.
Example 9-2. ReferencesDemo.java
/** "Walk, don't run" */
public
public class
class ReferencesDemo
ReferencesDemo {
// Assume this is an existing method we don't want to rename
public
public void
void walk () {
System . out . println ( "ReferencesDemo.walk(): Stand-in run method called" );
}
// This is our main processing method; it runs "walk" in a Thread
public
public void
void doIt () {
Runnable r = this
this :: walk ;
new
new Thread ( r ). start ();
}
// The usual simple main method to start things off
public
public static
static void
void main ( String [] args ) {
new
new ReferencesDemo (). doIt ();
}
}
The output is as follows:
ReferencesDemo.walk(): Stand-in run method called
Search WWH ::




Custom Search