Test for assignment using function

I was wondering if there is a test or some way to find out if the function is called for the assignment or not, I mean the difference between ...

int x = getX(); 

and just,

 getX(); 

This has no practical use, but I thought it would be good to know.

Is it possible?

+4
source share
2 answers

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.

+6
source

This is possible by analyzing the software bytecode, as Vulcan just put it right.

Think about it in practice, JRE. Therefore you need to break the operator

 int x = getX(); 

into two parts.

The first part that the JRE will execute will be getX and will result in something like

 int methodResult = getX(); 

The second part (which is the new instruction for the JRE) is similar to

 int x = methodResult; 

That's not all JRE does, but I think it helps to understand why there is no direct connection between the int x variable and the body of the getX method.

0
source

Source: https://habr.com/ru/post/1483978/


All Articles