+ Start a Discussion

APEX Class Instance Variable Losing Value

Hey All,


I have been beating myself up over this lately and am wondering if I am just doing something small incorrectly. I have a Visualforce Controller class that creates an instance of another Apex Class. While the page is loading, the methods in the instance run fine. However, when I try to print the state of the instance later, all of its variables have no value anymore, despite the fact that I have not cleared them. This results in me having to do a SOQL call again to repopulate them before running the methods again, which is costly and slow. Below is sample code of what I am doing:



public with sharing class myVisualForceCtrl {
	public ClassB myInstance;
	public myVisualForceCtrl() {
		myInstance = new ClassB();
	public void showState() {

public with sharing class ClassB {
	List<Account> testAccount;
	public ClassB() {
		testAccount = [SELECT Name FROM Account];
	public void printState() {
		System.Debug('CURRENT INSTANCE STATE: ' + testAccount);



During the initial page load, testAccount is correctly populated. However, I have a button on my visualForce page that runs the printState method again and does a reRender. This always shows the testAccount to be null.


Is this something I am doing incorrectly or is this the nature of Apex?


Thanks for any tips!


Probably has to do with what you are choosing to rerender. 


So you're saying you have a commandButton that does myInstance.printState()?


That isn't possible because printState doesnt return a PageReference.


Correct, it does not return a pagereference. What I placed above is psudo-code to isolate the issue. However, I have a get method to get the state. On the visualforce side I have an outputtext that is linked to that get. My button re-renders that outputtext, which calls the getState again and updates. On page load, it shows all the variables with their values. On a subsequent update it shows them all as null.


I know they are null because my other methods crash with a null pointer error.


Easiest if you post all the code.   Best, Steve.