You need to sign in to do that
Don't have an account?
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?
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
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()
}
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.