Newer Version Available
Create an Apex Class
You can use Salesforce CLI to create Apex classes in your local Salesforce DX project.
The generated class files live in a classes directory in a
package directory of your project.
- Open a terminal (macOS and Linux) or command prompt Windows and change to your Salesforce DX project directory.
- Create the classes directory in the location you want to generate the Apex class. For example, if you want to generate it in the default package directory, create the force-app/main/default/classes directory if it doesn’t exist.
-
Create the Apex class; specify the class name with the --name flag and the classes directory with the
--output-dir flag.
1sf apex generate class --name myClass --output-dir force-app/main/default/classes
The command generates two files:
- myClass.cls-meta.xml—metadata file
- myClass.cls—Apex source file
By default, the command creates an empty Apex class. However, you can select different templates, depending on what you’re creating, by specifying the --template flag.
| Template | Description | More Information in Apex Developer Guide |
|---|---|---|
| DefaultApexClass (default) | Standard Apex class. | Classes |
| ApexException | Use Apex built-in exceptions or create custom exceptions. All exceptions have common methods. | Exception Class and Built-in Exceptions |
| ApexUnitTest | Use the @isTest annotation to define classes and methods that only contain code used for testing your application. | isTest Annotation |
| InboundEmailService | Use email services to process the contents, headers, and attachments of inbound email. | Apex Email Service |
This example selects the ApexException template.
1sf apex generate class --name myException --template ApexException --output-dir force-app/main/default/classesUse the project deploy start command to deploy the new Apex class to your org.
1sf project deploy start --metadata ApexClass:myClass