We have a java process that calls some method of class X. Class X has timeout static field which decides how long thread should wait for in case of some error. Now, I want to change that value without changing my java process (I don't want deployment, and this change is experimental). How can I use java agent to change this timeout value to say 1 minute (1*60*1000)
Class X {
....
// timeout = 5 minutes
private static long timeout = 5*60*1000;
....
}
In short, how to write java agent to change value of a static variable. I have went through some tutorials, but none of those explain how to do this. I do not have access to main method. The project is run by an IOC container.
Thanks,
Rishi
Using reflection, you can implement this quite easily:
Note that this will change the field not before but right after class loading time. If this is not possible for you to work with, you might also just redefine the class itself what I would only recommend if:
If you want to really change the field before loading the class, you are lucky enough that you want to change the value of a field that is both
static
and that defines a primitive value. Such fields store their values directly at the site of the field. Using an agent, you can define aClassFileTransformer
that simply alters the value of the field on the fly. ASM is a good tool for implementing such a simple transformation. Using this tool, you could implement your agent approximately as follows:You can tell that this latter version requires a lot more code and requires your agent to be packed together with its ASM dependency.
To apply the agent, put either class in a jar file and put it onto the agent path.