1

In a recent question, I learned about seemingly magic variables/properties off of certain classes, such as SObjectType.Account, and SObjectType.Custom__c.

I also learned that if you have a method expecting an argument of type DescribeSObjectResult, you can pass in one of these magic properties, like SObjectType.Account and the Apex compiler is happy to accept it. It appears that somehow Saleasforce knows that it should call the getDescribe() method if one is passing in SObjectType.Account. Even then that doesn't make sense to me because getDescribe() is a member method of SObjectType based on the docs.

Also, from what I can tell, there's no documentation describing all the magic properties off of SObjectType. If you reference the docs for this class, it shows a messily 4 methods.

How is one supposed to know about the magic Account property off of Schema.sObjectType?

Why is it possible to pass Schema.sObjectType.Account as an argument in a method expecting DescribeSObjectResult?

1
  • I'd recommend avoiding adding memes to your questions. Mar 8, 2018 at 20:37

1 Answer 1

4

Short answer:

System.debug(Schema.SObjectType.Account instanceof Schema.DescribeSObjectResult); 

Result:

Operation instanceof is always true since an instance of Schema.DescribeSObjectResult is always an instance of Schema.DescribeSObjectResult


Schema.SObjectType is a generic type for the sake of having a generic type, which is why theres methods you can use to interact with it. Somewhere in the compiler, apex is smart enough to replace:

Schema.SObjectType.Account

With:

Account.SObjectType.getDescribe()

I'd think of it less of a magic variables/property, and more like an enum, which returns a type, which also has a generic base type.

You need the other methods for generic or unknown at compile time types. Having a generic type to use when you run something can be a real lifesaver:

SObjectType accountType = Schema.getGlobalDescribe().get('Account'); 

From the base generic type, you can call accountType.getDescribe() to get the actual describe.

2
  • Thanks for the answer. So Schema.SObjectType.Account doesn't actually exist, and the compiler creates Account.SObjectType.getDescribe() instead? How are we supposed to know this? Is there a list of compile-time translations for this and other classes/methods? Mar 8, 2018 at 21:13
  • 1
    Pretty much, yeah. Stuff like @isTest, "Account type binds to Schema.Account when namespace is null or empty" (from apex winter '18 compiler changes).. I'm sure theres a lot more, but a lot of it is under the hood, and not usually discussed - you'd have to talk to someone at salesforce to get the full scope of the compiler. If you want to learn more, check this video out: youtube.com/watch?v=Yc5FrviQqO8 Mar 8, 2018 at 21:23

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.