7

When I do a System.debug(whatever), SFDC doesn't care whether whatever is a String, a Date, a Datetime, a Boolean, etc... it just makes a string of it and dumps it in the log.

But in the following code:

    private static String transverse  (Case countryCase, String csvFieldName) {
SObject      currentSObject = countryCase;
String       fieldPath      = csvFieldName;

while (fieldPath.contains('.'))
{
    List<String> pathPartList   = fieldPath.split ('[.]', 2);

                 currentSObject = (SObject) currentSObject.getSobject(pathPartList[0]);
                 fieldPath      = pathPartList[1];
}

return (String) currentSObject.get(fieldPath);

SFDC will complain if the value is a Boolean, Date, Datetime, or maybe others(?).

I imagine that with some mapping and other complexity, I could first check the field type for currentSObject.get(fieldPath) and do some transformation/formatting before returning it... but that seems to be over-complicating things.

Is there any way to just dumping the value as if I were doing a System.debug()?

3 Answers 3

14

The String class has several static utility methods to transform a value into its string representation, like this:

String.valueOf(variableName);

That should solve your problem.

2

Just putting all of it together:

public static String toString(Object input) {
    if (input instanceof Date) {
        return ((Date) input).format();
    } else if (input instanceof Datetime) {
        return ((Datetime) input).format();
    } else if (input instanceof Decimal) {
        return ((Decimal) input).toPlainString();
    } else {
        return String.valueOf(input);
    }
}
1

Note: I found that with String.valueOf it would return scientific notation for a large decimal value... which I didn't like (caused issues for me) -- so I implemented the following code:

public static String getStringValue (Object theObj) {
    String strValue = String.valueOf( theObj );
    if ( theObj instanceof Decimal ) strValue = ((Decimal)theObj).toPlainString(); // Prevent scientific notation
    return strValue;
}

Thought I would share in case this helps someone else in the future.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .