How do I update a class variable from a trigger in Apex?
I've declared a class with a public variable LPAssign. I wanted to have an initial value of 1, which would then update every time a trigger is run.
Here's开发者_运维百科 my class:
public class LP {
public static integer LPAssign;
static{
LPAssign = 1;
}
}
And the code in my Trigger does this:
if LPAssign = 1, do several things, then update LPAssign =2.
if LPAssign = 2, do several things, then update LPAssign =3.
if LPAssign = 3, do several things, then update LPAssign =4.
if LPAssign = 4, do several things, then update LPAssign =1.
In my trigger I passed LPAssign on to a random field to see if it was changing to 2 (it does) but then my public class resets the value to 1. I thought the Static portion of the class only initialized once.
Static variables are only static for one execution thread, so if you're updating a record through the front end, and then updating it a second time when that thread has finished the second time your variable will be back at 1.
If you need to store the value between execution threads you're best off storing it in a field on an object — given the speed of the platform and the expanded governor limits these days that shouldn't really cause you a problem!
All that aside, if you're running the trigger multiple times in one thread you should be able to access a public static member without issue, I do it myself to stop cascading triggers etc.
精彩评论