Can you inspect the byte code of a Java 8 lambda at runtime?

后端 未结 4 1954
夕颜
夕颜 2021-01-31 18:22

If you have an anonymous class like

Predicate isEmpty = new Predicate() {
    public boolean test(String t) {
        return t.isEmpt         


        
4条回答
  •  说谎
    说谎 (楼主)
    2021-01-31 19:13

    The simple answer is: You can't. There is a related answer of Brian Goetz on this matter. For implementing lambda expressions, javac creates an INVOKEDYNAMIC instruction which delegates the invocation to the LambdaMetafactory's bootstrap method. For the OpenJDK, this bootstrap method is then creating an implementation of the required interface at runtime using ASM.

    Within the test method, the retreived instance tester is of this ASM-generated class such that you have no class file to read for finding out which method the Predicate represents. In the general case, the exact decision of how to map lambda expressions to interface implementations is left to the runtime environment what makes your problem even harder. The only way to find out which method a lambda expression represents is to read the byte code of its creation, i.e. interpreting the main method, for your example.

提交回复
热议问题