+ Start a Discussion

Generic get set function for visualforce and apex

Hello All,


I have a bit of a quandry. Excuse me if I'm a bit out of my element while trying to describe this, but here goes... I'd like to write a generic getter setter function in apex such that I can state any variable and have a single function handle the request. And I have to be able to use the get function from visualforce -- so I can't pass in a parameter into the function, correct? For instance, let's say I have three String variables.


String a;

String b;

String c;


And I write get functions as normal.


String getA() {return a;}

String getB() {return b;}

String getC() {return c;}


All is good and works easily with visualforce. But in my case I have possibly hundreds of variables, and would prefer not to write get function for every single one. I'm envisioning something like:


String get(String x) {return x;}


But, of course, that doesn't seem to work. Is there a way to make what I've described work?


Thanks in advance.



There's another way for getter/setter:


public String a {get;set;}


is the same as:


String a;

public String getA() {return a;}

public void setA(String v){a=v;}




Thanks PoorMan,


I'm looking for something a bit different. For instance, instead of writing this:


String a {get;set;}

String b {get;set;}

String c {get;set;}

//repeat x100 or more


i want to simply write one function that can handle many variables that can be retrieved via visualforce. Again, I don't think this works, but it's captures what I'm thinking.


String get(String x) {return x;}


Atleast then I would not have to write 100's of get/set statements but just 1.




Why not just use a Map?  I suspect if you have need you can even make your class an extension of Map.







Hey Bill,

May you little bit elaborate how to use map in this case?





<apex:outputText value="{!mymap['a']}"/>

<apex:outputText value="{!mymap['b']}"/>

 <apex:outputText value="{!mymap['c']}"/>


Google map reference in visualforce and you'll find some more interesting examples, as well as some bugs to avoid.   The biggest problem I've had with maps in visualforce is if you are not careful, you can end-up with run-time errors from undefined values.





Thanks Bill.