function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
TehNrdTehNrd 

Is it possible to dynamically reference variable names in a class?

I have a class where I am starting to see alot of the same code repeated and this is never ideal. Is there any way to refere to a variable name in a class dynamically? Below is what I have now. On my page I have a button that passes a param and clears this correct list. In my clear method I have alot of if else code.

 

It would be cool if I could somehow dynamically reference the Lists without have to hardcode the names. Is this possible?

 

 

Page:
<apex:commandButton value="Clear List" action="{!clearList}">
<apex:param value="divisions" assignTo="{!listToClear}"/>
</apex:commandButton>


Controller:
public String listToClear {get; set;}

List<cObject> divisions;
List<cObject> team;
List<cObject> infastructure;

public void clearList(){
if(listToClear == 'divisions'){
divisions = new List<cObject>();
}else if(listToClear == 'team'){
team = new List<cObject>();
}else if(listToClear == 'infastructure'){
infastructure = new List<cObject>();
}
}

 

Some like this. This code does not currently work:

 


public void clearList(){
this.get(listToClear) = new List<cObject>();
}

Is this even possible?

 

 

 

Message Edited by TehNrd on 09-02-2009 11:18 AM
Best Answer chosen by Admin (Salesforce Developers) 
TomSnyderTomSnyder

does not dynamically reference variable but you could do something like this.... 

 

 

public String listToClear {get; set;}

MAP<string,List<cObject>> = all new MAP<string,List<cObject>>(

'divisions'=>new List<cObject>(),

'team'=>new List<cObject>(),

'infastructure'=>new List<cObject>());


public void clearList(){
    this.get(listToClear).clear()
}

All Answers

TomSnyderTomSnyder

does not dynamically reference variable but you could do something like this.... 

 

 

public String listToClear {get; set;}

MAP<string,List<cObject>> = all new MAP<string,List<cObject>>(

'divisions'=>new List<cObject>(),

'team'=>new List<cObject>(),

'infastructure'=>new List<cObject>());


public void clearList(){
    this.get(listToClear).clear()
}

This was selected as the best answer
TehNrdTehNrd

Very nice. Why didn't I think of this! This has greatly reduced the amount of code required. 

 

Now if only visualforce pages could reference maps I could have one get method instead of what will probably be 15.

 

 

Message Edited by TehNrd on 09-02-2009 02:08 PM