[Salesforce] Using the with sharing or without sharing Keywords

本文介绍了如何在Apex中使用withsharing和withoutsharing关键字来控制类的权限,确保代码在运行时不因隐藏字段或对象而失败。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Use the  with sharing or  without sharing keywords on a class to specify whether or not to enforce sharing rules.

The with sharing keyword allows you to specify that the sharing rules for the current user be taken into account for a class. You have to explicitly set this keyword for the class because Apex code runs in system context. In system context, Apexcode has access to all objects and fields— object permissions, field-level security, sharing rules aren’t applied for the current user. This is to ensure that code won’t fail to run because of hidden fields or objects for a user. The only exceptions to this rule are Apex code that is executed with the executeAnonymous call and Chatter in ApexexecuteAnonymous always executes using the full permissions of the current user. For more information on executeAnonymous, seeAnonymous Blocks.

Use the with sharing keywords when declaring a class to enforce the sharing rules that apply to the current user. For example:

public with sharing class sharingClass {

// Code here

}

Use the without sharing keywords when declaring a class to ensure that the sharing rules for the current user are not enforced. For example:

public without sharing class noSharing {

// Code here

}
Some things to note about sharing keywords:
  • The sharing setting of the class where the method is defined is applied, not of the class where the method is called. For example, if a method is defined in a class declared with with sharing is called by a class declared with without sharing, the method will execute with sharing rules enforced.
  • If a class isn’t declared as either with or without sharing, the current sharing rules remain in effect. This means that if the class is called by a class that has sharing enforced, then sharing is enforced for the called class.
  • Both inner classes and outer classes can be declared as with sharing. The sharing setting applies to all code contained in the class, including initialization code, constructors, and methods.
  • Inner classes do not inherit the sharing setting from their container class.
  • Classes inherit this setting from a parent class when one class extends or implements another.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值