4
System.Type siteType = Type.forName('Site');
Site newSite = (Site) siteType.newInstance();

This fails with the error: System.TypeException: Invalid conversion from runtime type System.Site to Site

Reflection works in most cases for creating a new instance of an SObject, but in cases where there is also a system class with the same name we get that instead of the SObject. Is it possible to create a new instance of a Site SObject via reflection?

1 Answer 1

6

There's actually two Site objects, one in System and one in Schema. The former has a bunch of static methods like changePassword and createExternalUser, while the latter represents the sObject Site you're looking for. To get at that one, use its full name:

Type sitesObjectType = Type.forName('Schema.Site');
Site siteRecord = (Site)sitesObjectType.newInstance();
1
  • Perfect. In retrospect I should have been able to guess the namespace.
    – SSS
    Commented Dec 15, 2018 at 12:37

You must log in to answer this question.

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