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

后端 未结 4 2047
夕颜
夕颜 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:16

    After all, I found a way of getting hold of a lambda expression's class file that is rather reliable (but of course still relies on implementation details.) For an experimental implementation, I am now using a Java agent which allows for the retransformation of classes but which is itself implemented as a no-op, I am only interested in the binary array that is handed as an argument.

    After getting hold of an Instrumentation instance via the registered Java agent, one registers a ClassFileTransformer which is then notified over the binary representation once one retransforms lambdaInstance.getClass(). This is of course a rather hacky solution and might break once the internal implementation of lambdas is changed in the future.

    Unfortunately, I did not find any documentation on how an agent is supposed to behave with class retransformation of a lambda expression's synthetic class on a standards-compatible JVM.

提交回复
热议问题