LambdaMetafactory to access class on a different ClassLoader

前端 未结 2 2027
轻奢々
轻奢々 2021-01-14 15:56

I have this code which works fine:

Method getterMethod = Person.class.getDeclaredMethod(\"getName\");

MethodHandles.Lookup lookup = MethodHandles.publicLook         


        
2条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-14 16:36

    LambdaMetafactory's methods require you to pass PRIVATE lookup as their first parameter. Specification caller - Represents a lookup context with the accessibility privileges of the caller. might be a bit obscure, but it supposed to give the idea about the required privileges of the Lookup.

    Why does it have to be private? That's sort of future proofing the API. Remember that LambdaMetafactory is supposed to be invoked via invokedynamic instructions generated by compiler for lambdas. In that case VM will always pass the caller's MethodHandles.lookup() to the method, so the Lookup will always be PRIVATE. Using LambdaMetafactory directly in Java code is perfectly fine if you need it for your use case, but it isn't the primary usage, so the API is restricted to give just enough for the invokedynamic case but nothing more (other words - if invokedynamic works with PRIVATE then let's prohibit everything else just in case).

提交回复
热议问题