Generate an Apex Class.

You have the option to generate Apex classes using the CLI. By default, the class is generated in the directory where you initiate the command. The standard DX project template assumes that you intend to produce your Apex classes in the <package directory>/force-app/main/default/classes directory. To create classes in this specific directory, make sure to switch to it before executing the command.

sfdx force:apex:class:create -n myclass

If you find yourself in a different directory, you can use the “-d” parameter to specify either an absolute or relative path to designate the location where you wish to store your Apex class files. If you omit specifying an absolute or relative path and the directory doesn’t exist, the CLI will make an attempt to create it for you.

sfdx force:apex:class:create -n myclass -d ../force-app/main/default/classes

The command produces two files:

  • myclass.cls-meta.xml—metadata format
  • myclass.cls—Apex source file

The default behavior of the command is to generate a basic framework for an Apex class. Nevertheless, you have the option to choose from various templates based on your specific creation requirements.

TemplateDescriptionMore Information in Apex Developer Guide
DefaultApexClass (default)Standard Apex class.Classes
ApexExceptionUse Apex built-in exceptions or create custom exceptions. All exceptions have common methods.Exception Class and Built-in Exceptions
ApexUnitTestUse the @isTest annotation to define classes and methods that only contain code used for testing your application.isTest Annotation
InboundEmailServiceUse email services to process the contents, headers, and attachments of inbound email.Apex Email Service