3

From the documentation > SObjectType Class I see that we can instantiate a new sObject from the SObjectType class

Could you tell me how does the code below create a new Account regarding the required fields

Account newAcc = (Account)Account.sObjectType.newSObject();

Are the required fields ignored or are they filled with some default values ?

1
  • 1
    You have just created an empty object and it's reference is assigned to newAcc. When you try to insert that object by performing DML then necessary validations rules get fired and if any required field is missing, it will throw error. Mar 17, 2017 at 13:54

2 Answers 2

4

It will simply instantiate a new empty Account object.

Required fields only come into play when you perform the DML. You will have to set those.

This and the describe classes are useful when the object type in a method can vary and be identified during runtime.

1
  • Indeed, for example if you write a package that can do arbitrary things to arbitrary records (like the popular Declarative Rollups package), you need to be able to take a given SObject type and create a new instance of that type.
    – Charles T
    Mar 17, 2017 at 15:02
3

From the documentation:

Constructs a new sObject of this type

Basically:

Account newAcc = (Account)Account.sObjectType.newSObject();

is same as:

Account newAcc = new Account();

It returns the instance of Object, you would need to populate additional fields yourself.

Here is an example to validate it:

Account objAccountobject = (Account)Account.sObjectType.newSObject();

Account objAccount = new Account();

System.debug('This would be true' + objAccountobject == objAccount);

You must log in to answer this question.

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