Yes, it is possible, but only by analyzing the compiled bytecode of the program, which makes it extremely inconvenient. Bytecode can be obtained at runtime by receiving class bytes (either through instrumentation or other methods) and then parsed using third-party libraries such as ASM , BCEL, or Javassist .
To search for a local variable that is assigned the result of a function, you must look for the following bytecode pattern:
invokevirtual/static [class:method()signature] xstore #stack
For the exact case, int x = getX(); the bytecode will look like:
invokevirtual [clazz:getX()I] istore 1
But of course, clazz is the actual class that getX() , and the stack value of the saved local variable ( xstore ) will probably be different. In addition, invokeXXX will be followed by loading method arguments, including the implicit this instance.
In general, this is possible, but not convenient, since understanding the bytecode is not one-day.
source share