How to get Apex Class Access for a profile using Apex in Salesforce?

How to get Apex Class Access for a profile using Apex in Salesforce?

Apex Classes assignment to a Profile are stored in SetupEntityAccess entity/object. So, by filtering ParentId with the Profile’s Permission Set Id and SetupEntityType = ‘ApexClass’, we can fetch the Apex Classes that are assigned to a Profile using Apex in Salesforce.

Sample Code:

Id profileId = [
	SELECT Id
	FROM Profile
	WHERE Name = 'Read Only'
].Id;
Id permissionSetId = [
	SELECT Id 
	FROM PermissionSet 
	WHERE ProfileId =: profileId
].Id;
List < SetupEntityAccess > listApexClassAccess = [
	SELECT SetupEntityId 
	FROM SetupEntityAccess 
	WHERE ParentId = :permissionSetId AND SetupEntityType = 'ApexClass'
];
Set < Id > setApexClassIds = new Set < Id >();

for ( SetupEntityAccess objSEA : listApexClassAccess ) {

	setApexClassIds.add( objSEA.SetupEntityId );
	
}

List < ApexClass > listApexClasses = [ 
	SELECT Name
	FROM ApexClass
	WHERE Id IN: setApexClassIds
];

for ( ApexClass objApexClass : listApexClasses ) {

	System.debug( objApexClass.Name );
	
}

Output:

Leave a Reply