I am currently using ASM to intercept all attempts to mutate field values in a target application this is working as expected as ASM allows you to prepend or append instructions to method or constructor code segments.
However, it occurred to me that its a fairly common developer paradigm to initialize fields outside the scope of a Method or Constructor for example:
public class Example{
//--VARIABLE INITIALIZATION OUTSIDE METHOD OR CONSTRUCTOR SCOPE ---
private String aString = "A String Value";
//zero argument constructor
public Example(){
}
//all other methods.
}
My question is: how would one approach the task of Intercepting field access made in this way i.e out side the context of a Method or Constructor?
This looks like it’s outside the constructor in the source code, but in fact in the bytecode the initializers are all part of the constructor(s) – they get “moved” into the constructor by the compiler. The initializers are placed after the implicit or explicit
super()call but before the rest of the constructor’s code. In particular this means that if you have a situation like this:then
new Sub();would printas the
in doSomeStuffprint happens before theSubfield initializers have run.