How to add Apex Class Access to permission set programmatically

  • Salesforce provides an object SetupEntityAccess where field’s permission is stored for a permission set.
  • Programmatically it’s only possible for Permission Set not for Profile.
  • Here is Salesforce help article: https://developer.salesforce.com/docs/atlas.en-us.sfFieldRef.meta/sfFieldRef/salesforce_field_reference_SetupEntityAccess.htm
insert new SetupEntityAccess(
        ParentId = '0PS...', // PermissionSet ID
        SetupEntityId = '01p...' // ApexClass ID
);

In case if you are looking further, how to assign such permission sets to users automatically, here is answer: http://sfdcian.com/assigning-permission-set-to-user-in-apex/