Apex 入门教程
学习目标
完成本单元后,您将能够:
- 描述 Apex 编程语言的主要特性。
- 保存 Apex 类并使用匿名 Apex 调用类方法。
- 使用 Web Console(Web 控制台)检查调试日志。
开始之前
我们很高兴跟您一起探索 Apex。此模块将介绍编程语言的基本信息,也会快速深入。如果这是您首次了解 Apex,我们强烈建议您先完成快速入门:Apex 项目, 然后回来, 我们等您!
Apex 是什么?
Apex 是一种编程语言,它具有类似 Java 的语法,其用法与数据库存储过程类似。Apex 允许开发人员将业务逻辑添加到系统事件中,例如按钮的点击、相关记录的更新以及操作 Visualforce 页面等。
作为一种编程语言,Apex 具有以下特点:
-
可托管 — Apex 在 Salesforce Platform 服务器上保存、编译和执行。
-
面向对象 — Apex 支持类、接口和继承。
-
强类型 — Apex 会在编译过程中验证对对象的引用。
-
多租户防范 — 由于 Apex 在多租户平台上运行,因此通过实施限制来严密防范代码失控。这些限制有助于防止代码独占共享资源。
-
与数据库集成 — 直接访问并操作记录。Apex 可直接访问记录和其字段,并提供操作这些记录的语句和查询语言。
-
数据集中 — Apex 支持数据库的事务性访问,允许回滚操作。
-
使用简便 — Apex 基于熟悉的 Java 习惯用语。
-
测试方便 — Apex 为单元测试的创建、执行和代码覆盖提供内置支持。
-
版本控制 — 针对不同版本的 API 保存自定义 Apex 代码。

Apex 语言的亮点
与其他面向对象的编程语言一样,Apex 支持以下语言结构:
- 类、接口、属性和集合(列表、映射和集合)。
- 对象和数组符号。
- 表达式、变量和常量。
- 条件语句 (if-then-else) 和控制流语句(for 循环和 while 循环)。
不同于其他面向对象的编程语言,Apex 支持以下特性:
- 云开发,即 Apex 在云上存储、编译和执行。
- 触发器,类似于数据库系统中的触发器。
- 数据库语句,允许直接调用数据库和查询语言,以查询和搜索数据。
- 事务和回滚。
-
global访问修饰符,比public修饰符更加宽松,允许在命名空间和应用程序之间访问。
- 自定义代码的版本控制。
此外,Apex 语言不区分大小写。
开发工具
您可以使用 Salesforce Extensions for Visual Studio Code 在您的客户端电脑上编写和调试 Apex。参见使用 Salesforce 扩展轻松开发。
您还可以直接在浏览器中使用 Salesforce 的用户界面编写 Apex 并访问调试信息。Web Console(Web 控制台)是一款现代化、轻量级、基于浏览器的集成开发环境 (IDE),旨在弥合老旧工具与高开销开发环境之间的差距。有关详细信息,请参阅 Web Console(Web 控制台)开发人员文档。
您可以通过快速访问菜单 (
) 打开 Web Console(Web 控制台)。

数据类型概览
Apex 支持多种数据类型,包括 Salesforce 独有的数据类型 — sObject 数据类型。
Apex 支持以下数据类型。
-
基元,例如 Integer、Double、Long、Date、Datetime、String、ID、Boolean 等。
-
sObject,包含泛型 sObject 和特定 sObject,例如客户、联系人或 MyCustomObject__c。(您会在后续单元中了解关于 SObject 的更多信息。)
- 集合,包括:
-
一种列表——一种有序的、带索引的元素集合。列表元素可以是任意数据类型,包括基本类型、集合、sObject、用户自定义类型以及系统提供的(内置)Apex 类型。
- 一种集合——一种无序的元素集合。集合元素同样可以是任意数据类型,且不能包含重复值。
- 一种映射——一种由键值对组成的集合,可以是任意数据类型。
- 类型化的值列表,也被称为枚举
- 用户定义的(自定义)Apex 类
- 系统提供的(内置)Apex 类
Apex 集合:List
列表保存相同类型的有序数据集合。
以下两个声明是等效的。通过 List 语法声明 colors 变量。
List<String> colors = new List<String>();
或者,可以使用数组符号来声明 colors 变量。
String[] colors = new List<String>();
根据需要用 List.add() 方法添加新元素来扩大集合。您可以使用方括号数组符号按索引引用集合中的现有元素。但是您不能用方括号数组符号添加更多元素。
此示例显示创建列表后,如何向列表添加元素,然后用 add() 方法添加更多元素。
// Create a list and add elements to it in one step
List<String> colors = new List<String> { 'red', 'green', 'blue' };
// Add elements to a list after it has been created
List<String> moreColors = new List<String>();
moreColors.add('orange');
moreColors.add('purple');可以通过在方括号之间指定索引来读取列表元素,这称为数组符号。同样,您也可以通过 get() 方法来获取 list 元素。此示例基于上一个示例中创建的列表,并展示了如何使用任一方法来读取 list 元素。该示例还展示了如何遍历列表元素。
// Get elements from a list
String color1 = moreColors.get(0);
String color2 = moreColors[0];
System.assertEquals(color1, color2);
// Iterate over a list to read elements
System.debug('Print out the colors in moreColors:');
for(String color : moreColors) {
// Write value to the debug log
System.debug(color);
}进阶学习
Apex 同样支持 Set 和 Map 两种集合类型。有关这些内容的更多信息,请参见 Apex 开发人员指南中的 Collections 部分。
Apex 类
Apex 类的优点之一就是代码的复用性。类中的方法能被触发器或其他类调用。以下教程为您演示如何在组织中保存示例类、使用该类更新客户描述以及检查调试日志。
保存 Apex 类
AccountProcessor 类包含一个公共方法 updateAccountDescriptions()。该方法接收一个客户列表,并按照私有辅助方法 applyStandardFormatting() 中指定的格式更新这些客户的描述。私有辅助方法无法从外部调用,仅可在类内部调用。AccountProcessor 类还包含私有辅助方法 inspectResults(),用于检查更新数据库操作的结果。
在 Trailhead 组织中保存 AccountProcessor 类。
- 通过快速访问菜单 (
) 打开 Web Console(Web 控制台)。
- 在 Web Console(Web 控制台)中,按 Ctrl+Shift+P (Windows) 或 ⌘+Shift+P (macOS) 打开命令面板。
- 输入
SFDX: Create Apex Class(SFDX:创建 Apex 类),然后按 Enter 键。
- 对于模板类型,请选择 DefaultApexClass,然后按 Enter 键。
- 对于类名称,请输入
AccountProcessor,然后按 Enter 键。
- 对于输出目录,请选择 force-app/main/default/classes,然后按 Enter 键。
- 用
AccountProcessor类示例替换默认类主体。
public with sharing class AccountProcessor {
/**
* Applies a standard formatting to the descriptions of accounts in the list,
* and updates each account.
*/
public void updateAccountDescriptions(List<Account> acctList) {
if (acctList == null || acctList.isEmpty()) {
System.debug('Account list is null or empty.');
return;
}
for (Account acc : acctList) {
applyStandardFormatting(acc);
}
Database.SaveResult[] srList = Database.update(acctList,
false,
AccessLevel.USER_MODE);
inspectResults(srList);
}
/**
* Private helper method to handle the description formatting logic.
*/
private static void applyStandardFormatting(Account acc) {
String timestamp = String.valueOf(Datetime.now());
if (String.isBlank(acc.Description)) {
acc.Description = 'Account updated on: ' + timestamp;
} else {
acc.Description += ' | Last processed: ' + timestamp;
}
}
/*
* Private helper method to inspect the returned results.
*/
private static void inspectResults(Database.SaveResult[] results) {
for (Database.SaveResult sr : results) {
if (sr.isSuccess()) {
System.debug('Successfully updated account. Account ID: ' + sr.getId());
} else {
for (Database.Error err : sr.getErrors()) {
System.debug('The following error has occurred.');
System.debug(err.getStatusCode() + ': ' + err.getMessage());
System.debug('Account fields that affected this error: ' +
err.getFields());
}
}
}
}
}- 要保存该类,按 Ctrl+S (Windows) 或 ⌘+S (macOS)。
保存类后,Salesforce 会编译并部署该类。
进阶学习
您刚刚保存的类使用了面向对象编程 (OOP)。该类封装了与电子邮件管理相关的方法。OOP 完美示例中的类还将包含用于访问这些属性的成员变量(属性)和访问器方法,但为了简单起见,我们的类没有这些属性。
调用方法更新 Account Description(客户描述)
让我们调用公共方法吧。我们将使用匿名 Apex 来执行此操作。匿名 Apex 允许您动态运行代码行,是调用 Apex 的一种简便方法,尤其适用于功能测试。与其他 Apex 执行一样,也会生成调试日志结果。
- 在 Web Console(Web 控制台)中,按 Ctrl+Shift+P (Windows) 或 Cmd+Shift+P (macOS) 打开命令面板。
- 输入
SFDX: Create Anonymous Apex Script,然后按 Enter 键。
- 对于类名称,请输入
UpdateAccounts,然后按 Enter 键。
- 对于输出目录,请选择 scripts/apex,然后按 Enter 键。
- 输入以下代码。
// Create new accounts
List<Account> newAccts = new List<Account>();
newAccts.add(new Account(Name='My New Account', Description='Original Description'));
newAccts.add(new Account(Name='My Second New Account'));
// Insert them into the database
try {
insert as user newAccts;
System.debug('Successfully inserted ' + newAccts.size() + ' accounts.');
} catch (Exception e) {
System.debug('An error inserting the records occurred: ' + e.getMessage());
}
// Instantiate an AccountProcessor object
AccountProcessor myAcctProcessor = new AccountProcessor();
// Pass the original list to update the account descriptions
myAcctProcessor.updateAccountDescriptions(newAccts);- 要保存脚本,按 Ctrl+S (Windows) 或 ⌘+S (macOS)。
- 要运行脚本,请在文本编辑器中右键单击,然后选择 SFDX: Execute Anonymous Apex with Currently Open Editor(SFDX:使用当前打开的编辑器执行匿名 Apex)。
- 在 Salesforce 中,打开 My New Account(我的新客户)和 My Second New Account(我的第二个新客户)的记录详情页面。
My New Account(我的新客户)的 Description(描述)字段应为 Original Description | Last processed: 2026-01-01 00:00:00,My Second New Account(我的第二个新客户)的 Description(描述)字段应为 Account updated on: 2026-01-01 00:00:00,但请注意,两个时间戳都将反映执行匿名 Apex 事务时的时间和日期。
查看调试日志
调试日志对调试代码很有帮助。当执行 Apex 方法时,所有调用情况都会记录在调试日志中。当然您也可以在日志中写入自己的调试消息,帮助您调试代码以确定是否包含错误信息。inspectResults() 辅助方法由 updateAccountDescriptions() 调用,通过使用 System.debug() 方法将消息写入日志,以指示数据库更新操作成功还是发生错误。您可以在执行该方法时生成的调试日志中查找这些消息。
- 在 Web Console(Web 控制台)中运行 UpdateAccounts 脚本后,打开 Output(输出)面板。
- 选择 Debug Only(仅调试)筛选日志,只显示
System.debug()语句的日志行。
- 在 Output(输出)面板顶部的 filter(筛选)字段中,输入
USER_DEBUG以筛选日志,使其仅显示System.debug()语句的日志行。
- 您也可以在 .sfdx/tools/debug/logs 目录中查看调试日志。

假设脚本运行没有错误,您将在已筛选的日志视图中看到以下消息。
DEBUG|Successfully inserted 2 accounts.
DEBUG|Successfully updated account. Account ID: {id}
DEBUG|Successfully updated account. Account ID: {id}调用静态方法
由于类中的 updateAccountDescriptions() 方法没有访问类中的成员变量,因此不需要使用实例方法。现在我们将这个方法改成静态方法,即在方法声明中添加 static 关键字。静态方法的调用比实例方法更简便,它不需要在类的实例上调用,而是直接通过类名来调用。
- 在 Web Console(Web 控制台)中,打开
AccountProcessor.cls类文件。
- 修改
updateAccountDescriptions()定义的第一行。唯一的改动是添加了static(静态)关键字。
public static void updateAccountDescriptions(List<Account> acctList) {- 要保存类,按 Ctrl+S (Windows) 或 ⌘+S (macOS)。保存后,类将重新部署。
- 打开
UpdateAccounts.apex匿名 Apex 脚本文件。
- 将当前代码替换为以下代码,使脚本通过类名调用静态方法。
// Create new accounts
// For clarity, use different account names than the ones you used previously
List<Account> newAccts = new List<Account>();
newAccts.add(new Account(Name='My Third New Account', Description='Original Description'));
newAccts.add(new Account(Name='My Fourth New Account'));
// Insert them into the database
try {
insert as user newAccts;
System.debug('Successfully inserted ' + newAccts.size() + ' accounts.');
} catch (Exception e) {
System.debug('An error inserting the records occurred: ' + e.getMessage());
}
// Pass the original list to update the account descriptions
// The static method is called directly on the class
AccountProcessor.updateAccountDescriptions(newAccts);- 要保存脚本,按 Ctrl+S (Windows) 或 ⌘+S (macOS)。
- 要运行脚本,请在文本编辑器中右键单击,然后选择 SFDX: Execute Anonymous Apex with Currently Open Editor(SFDX:使用当前打开的编辑器执行匿名 Apex)。现在已经执行了此方法,您可以在 Salesforce 中验证已更新的客户描述,还可按需参照前述步骤查看调试日志。
资源
