lundi 6 avril 2020

Inner Lambda getting returned in Class.getDeclaredMethods()?

Consider this class:

public class Handler
{
    private Supplier<Foo> foo;

    public void handle( Bar bar )
    {
        foo = () -> bar.getFoo();
    }
}

And consider this reflection snippet which wants to access the handle() method.

for( Method method : Handler.class.getDeclaredMethods() )
{
    if ( method.getParameterCount() == 1 && Bar.class.isAssignableFrom( method.getParameterTypes()[0] ) )
    {
        // This is the method you are looking for
    }
}

Instead of finding

  • public void Handler.handle(Bar)

It finds

  • private Foo Handler.lambda$3(Bar)

Which obviously then throws the Exception:

java.lang.IllegalAccessException: class HandlerService cannot access a member of class Handler with modifiers "private static"

Can someone explain what is going on here, please?

It looks like Java considers the lambda inside the method as a top-level declared method. Is this new (or even a bug) in Java 11 ?





Aucun commentaire:

Enregistrer un commentaire