You need to sign in to do that
Don't have an account?

Java-like Reflective Field Access in Apex?
In Java you can access a class's fields using the reflective method getField(String name). Is something like this possible in Apex?
For example, instead of accessing with simple dot notation:
String lname = Contact.lastName;
Is there a way to do something like this:
String lname = Contact.getField('lastName');
I'm trying to access a field where I'm pulling the field name from a variable, but I obviously can't do something like.
String.myVar = "lastName";
String lname = Contact.myVar;
I can set this up with a block of if statements (like a switch statement), but if there's a way to do it with reflection, that seems more elegant to me. I'm going to be testing for a lot of values so it would certainly be more concise (1 line of code vs n lines, where n is the number possible values).
if(myVar == "lastName" ) {lname = Constant.lastName}
I'm guessing the answer is no, because I don't see it in the manual...
-paul
All Answers
Ah, thanks, that's exactly what I was looking for.
I think I can actually avoid the whole thing entirely by using Dynamic SOQL, because I'm trying to filter results based on a query parameter. But the sObject get method does what I was asking about.
This will make my unit testing much easier.
thanks a lot,
-paul
Hi..
Is the same thing possible with Visualforce page also?
I have implemented it in Apex class. I'm using one List of Strings, wherein i'm keeping the names and using that list for retrieving values, instead of hard coding it.
Now, is it possible to have with VF COde also?
Suvra,
I don't know what you mean. What are you talking about when you say "Is the same thing possible with Visualforce page[/code] also"? Visualforce is not a programming language. I'm pretty sure you can't do something like "{!field('lastName')}"
if that's what you mean.
I was trying to dynamically access fields based on URL query parameters (aka GET parameters) at runtime. So I needed something like this, but in my case dynamic SOQL sufficed.
You could use that reflective getField method to make a getter method in your apex to get something. But it sounds like you are trying to iterate over a list. If so try reading the documentation for one of the iterative components in Visualforce, like dataTable or repeat.
-paul
That works on custom database objects but not on custom classes.
It would be great if Apex custom classes had a parent class with some reflective behavior, like a list of its properties, a list of its variables, a list of its methods and their argument types, etc..