apex - Create Class object through class name in Salesforce -
i new salesforce , want code 1 requirement, have api name in string variable through want create object of class.
for eg. object name account stored in string variable. string var = 'account'
now want create object of 'account'. in java possible class.forname('account') similar approach not working in salesforce apex.
can please me out in this.
have @ type class. documentation isn't terribly intuitive, perhaps you'll benefit more article introduced it: https://developer.salesforce.com/blogs/developer-relations/2012/05/dynamic-apex-class-instantiation-in-summer-12.html
i'm using in managed package code inserts chatter posts (feed items) if org has chatter enabled:
sobject fitem = (sobject)system.type.forname('feeditem').newinstance(); fitem.put('parentid', userinfo.getuserid()); fitem.put('body', 'bla bla bla'); insert fitem;
(if i'd hardcode feeditem
class & insert directly it'd mark package "requires chatter run").
alternative build json representation of object (string not type field values). have @ https://salesforce.stackexchange.com/questions/171926/how-to-deserialize-json-to-sobject
at least know keywords & examples search :)
edit:
based on code snippet - try this:
string typename = 'list<account>'; string content = '[{"attributes":{"type":"account"},"name":"some account"},{"attributes":{"type":"account"},"name":"another account"}]'; type t = type.forname(typename); list<sobject> parsed = (list<sobject>) json.deserialize(content, t); system.debug(parsed); system.debug(parsed[1].get('name')); // , if need write code "if it's accounts special them": if(t == list<account>.class){ list<account> accs = (list<account>) parsed; accs[1].billingcountry = 'usa'; }
Comments
Post a Comment