You can achieve this using JSON.serialize and JSON.deserialize, as described in my answer to this question: Can I tell which fields are present in an SObject variable?
Suppose you have a class MyClass
, with two attributes att1
and att2
. We then add a method getAttributes()
to return a Set<String>
containing the names of the attributes on that object:
public class MyClass
{
public String att1;
public Decimal att2;
public Set<String> getAttributes()
{
// Serialize our Object into JSON
String s = JSON.serialize(this);
// Deserialize it back into a key/value map
Map<String,Object> obj =
(Map<String,Object>) JSON.deserializeUntyped(s);
// Return a Set of those fields present on our object
return obj.keyset().clone();
}
}
Which can be used like so:
MyClass c = new MyClass();
Set<String> attrs = c.getAttributes();
system.debug(attrs);
// ==> {'att1','att2'}
To dynamically walk through the attribute values, I would probably leverage System.JSONParser
, which would let you walk through the attributes in an object/class, and provide you with both the ability to obtain the value of the attribute, and its type:
MyClass c = new MyClass();
c.att1 = 'foobar';
c.att2 = 100.1;
String jsonContent = JSON.serialize(c);
// ==> '{"att1":"foobar","att2",100.1}';
JSONParser parser =
JSON.createParser(jsonContent);
// Advance to the start object marker.
parser.nextToken();
// Advance to the next value.
JSONToken t = parser.nextValue();
// Get the JSON type of the current value / token,
// which is an ENUM of valid JSON types
// (see http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_methods_system_jsonparser.htm)
if (t == JSONToken.VALUE_NUMBER_FLOAT){
system.debug('got a floating point number!');
Decimal decimalValue = parser.getDecimalValue();
} else if (t == JSONToken.VALUE_STRING){
// Here, to determine advanced Apex object types,
// you may have to apply some Regex or try/catch conversion
//
String stringValue = parser.getText();
if (stringValue.split('-').size()==3){
// We have a Salesforce Date value
Date dateValue = parser.getDateValue();
} else {
// and so on for other Apex primitives
// that are stored in JSON as Strings.
}
}