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?


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();
| improve this answer | |
  • Perfect. In retrospect I should have been able to guess the namespace. – SSS Dec 15 '18 at 12:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.