Method References

Fredrik Öhrström fredrik.ohrstrom at oracle.com
Sun Feb 28 01:39:36 PST 2010


Reinier Zwitserloot wrote:
> Is this really necessary? If the signature of saveState is:
>
> void saveState() {
>     ...
> }
>
> then instead of adding syntax so you can write:
>
> #void() saveStateRef = this#saveState;
>
> you can just use the existing closures status quo:
>
> #void() saveStateRef = #() {saveState();};
>
>   
Is this closure syntax really necessary?
You can just use the existing anon.inner.class status quo:

Callable<Void> saveStateRef = new Callable<Void> () {
        public Void call() { saveState(); return null;}};

**joke-end**

Yes, method references are necessary since their use case is extremely
common. The most common use case should have the shortest syntax.
Also the method ref syntax avoids the risk of binding locals.

MethodHandles are in effect method references. Assuming MHs are used
to construct closures then, then the building block for closures are method
references, not the other way round.

Thus the this#saveState will be compiled into the following bytecode:
   ldc MyApp.saveState()V
   aload 0
   invokevirtual MethodHandle.bindTo(LObject;)LMethodHandle;

"ldc non-static-methodref" will create a virtual MethodHandle (aka 
stored message) with the signature
invokeGeneric(MyApp)V
when we bind this MethodHandle to an instance (ie this, stored in local 
var 0) the signature changes to:
invokeGeneric()V

Neat, eh?

//Fredrik



More information about the lambda-dev mailing list