2

I have a wrapper class. In that i need to access the property and its value at run time. From the code below,

Wrapper class:

    public with sharing class SalesOrderWrapper implements Comparable {
        public Integer OrderNo {get; set;}
        public String PurchaseOrderNo {get; set;}
        public String SalesOrg {get; set;}
        public String Amount {get; set;} 
//**********remaining code goes here**********

Now, i need to access the value of the above properties (OrderNo, PurchaseOrderNo, etc) at run time without hardcoding the syntax like this...

SalesOrderWrapper SOWrapper = (SalesOrderWrapper) compareTo;
SOWrapper.OrderNo    

to something like this so that the value for "s" will be decided at the run time. Is this reflection kind of thing possible only with sObjects or with custom type too? Kindly edit the question if i did not frame the question correctly.

String s = 'OrderNo'
SOWrapper.get(s);

I know for sobject it works as below.

Account ac = new Account();
Id acId = ac.get('Id');

Is the same thing possible with custom type? Please suggest.

1 Answer 1

2

Unfortunately, you can't do this with a wrapper class. The get() method is on SObject. A wrapper class is not considered an SObject. If you attempt to extend SObject with an Apex class, you get the following error:

Cannot extend SObject

The reason for this is that the SObject methods are typically heavily dependent on the Schema namespace. These methods provide you with functionality directly related to your schema (aka, your data structure). Unfortunately, this wrapper class is not considered to be part of the schema so none of the underlying functionality that the SObject would provide would work for a wrapper class.


With that said, you could always write your own get(String fieldName) method to perform something similar for your wrapper class. Something like:

public class TestWrapperClass{
    public Integer OrderNo {get; set;}
    public String PurchaseOrderNo {get; set;}
    public String SalesOrg {get; set;}
    public String Amount {get; set;}

    public Object get(String fieldName){
        if(fieldName == 'OrderNo'){
            return OrderNo;
        }

        if(fieldName == 'PurchaseOrderNo'){
            return PurchaseOrderNo;
        }

        if(fieldName == 'SalesOrg'){
            return SalesOrg;
        }

        if(fieldName == 'Amount'){
            return Amount;
        }

        return null;
    }
}

While you would have to maintain this and it would not be dynamic (as in, every time you add a field to the wrapper class you need to update this method), it should work in a similar fashion to how the SObject.get() method works.

1
  • 1
    Thanks Jesse. Great suggestion for an alternate approach to achieve "dynamic like" solution.
    – Bforce
    Apr 17, 2014 at 16:13

You must log in to answer this question.

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