Apex Classes and Casting

通常,所有类型信息在运行时都可用。这意味着 Apex 启用强制转换,即将一个类的数据类型分配给一个数据 另一个类的类型,但仅当一个类是另一个类的子类时。使用铸造 当您要将对象从一种数据类型转换为另一种数据类型时。

在以下示例中,扩展 类 .因此,它是一个子类 那个班级。这意味着您可以使用强制转换将对象与父对象一起分配 数据类型 () 添加到对象的 子类数据类型 ()。CustomReportReportReportCustomReport

public virtual class Report {
}
public class CustomReport extends Report {
}

在下面的代码段中,首先将自定义报表对象添加到报表列表中 对象。然后,自定义报表对象将作为报表对象返回,然后 强制转换回自定义报表对象。

...
  // Create a list of report objects
  Report[] Reports = new Report[5];

  // Create a custom report object
  CustomReport a = new CustomReport();

  // Because the custom report is a sub class of the Report class,
  // you can add the custom report object a to the list of report objects
  Reports.add(a);

  // The following is not legal:
  // CustomReport c = Reports.get(0);
  // because the compiler does not know that what you are
  // returning is a custom report. 

  // You must use cast to tell it that you know what
  // type you are returning. Instead, get the first item in the list
  // by casting it back to a custom report object
  CustomReport c = (CustomReport) Reports.get(0);
...

此外,接口类型可以强制转换为子接口或类类型,该类类型 实现该接口。

提示

若要验证类是否为特定类型的类,请使用关键字。有关更多信息,请参阅使用 instanceof 关键字instanceOf

类和集合

列表和映射可以与类和接口一起使用,其方式与列表和映射相同 与 sObject 一起使用。这意味着,例如,您可以将用户定义的数据类型用于 value 或映射的键。同样,您可以创建一组用户定义的对象。

如果创建映射或接口列表,则 接口可以放入该集合中。例如,如果 List 包含一个接口,并实现 ,然后可以 被放置在列表中。

Collection Casting

由于 Apex 中的集合在运行时具有声明的类型,因此 Apex 允许集合转换。

集合可以采用与数组类似的方式进行强制转换 在 Java 中投射。例如,CustomerPurchaseOrder 对象的列表 如果 class 是子对象,则可以分配给 PurchaseOrder 对象列表 的类。CustomerPurchaseOrderPurchaseOrder

public virtual class PurchaseOrder {

    Public class CustomerPurchaseOrder extends PurchaseOrder {

    }
    {
        List<PurchaseOrder> POs = new PurchaseOrder[] {};
        List<CustomerPurchaseOrder> CPOs = new CustomerPurchaseOrder[]{};
        POs = CPOs;
    }
}

将列表分配给列表变量后,就可以将其强制转换 返回到 CustomerPurchaseOrder 对象的列表,但只是因为该实例是 最初实例化为 CustomerPurchaseOrder 对象的列表。列表 实例化的 PurchaseOrder 对象不能强制转换为 CustomerPurchaseOrder 对象,即使 PurchaseOrder 对象列表仅包含 CustomerPurchaseOrder 对象。CustomerPurchaseOrderPurchaseOrder

如果仅包含 CustomerPurchaseOrders 的 PurchaseOrder 列表的用户 objects 尝试插入 的非 CustomerPurchaseOrder 子类(例如 ),运行时 异常结果。这是因为 Apex 集合在运行时具有声明的类型。PurchaseOrderInternalPurchaseOrder

注意

地图的行为方式与列表在地图的值方面相同。如果值 映射 A 的一侧可以强制转换为映射 B 的值侧,并且它们具有相同的键类型, 然后可以将映射 A 投射到映射 B。如果强制转换无效,则会导致运行时错误 在运行时使用特定映射。