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:
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: