Newer Version Available

This content describes an older version of this product. View Latest

NamespaceAccessible Annotation

The @namespaceAccessible makes public Apex in a package available to other packages that use the same namespace. Without this annotation, Apex classes, methods, interfaces, properties, and abstract classes defined in a 2GP package aren’t accessible to the other packages with which they share a namespace. Apex that is declared global is always available across all namespaces, and needs no annotation.

For more information on 2GP managed packages, see Second-Generation Managed Packages in Salesforce DX Developer Guide.

Considerations for Apex Accessibility Across Packages

  • You can't use the @namespaceAccessible annotation for an @AuraEnabled Apex method referenced from a Lightning component.
  • You can add or remove the @namespaceAccessibleannotation at any time, even on managed and released Apex code. Make sure that you don’t have dependent packages relying on the functionality of the annotation before adding or removing it.
  • When adding or removing @namespaceAccessible Apex from a package, consider the impact to customers with installed versions of other packages that reference this package’s annotation. Before pushing a package upgrade, ensure that no customer is running a package version that would fail to fully compile when the upgrade is pushed.
This example shows an Apex class marked with the @namespaceAccessible annotation. The class is accessible to other packages within the same namespace. The first constructor is also visible within the namespace, but the second constructor isn’t.
1// A namespace-visible Apex class
2@namespaceAccessible
3public class MyClass {
4    private Boolean bypassFLS;
5
6    // A namespace-visible constructor that only allows secure use
7    @namespaceAccessible
8    public MyClass() {
9        bypassFLS = false;
10    }
11
12    // A package private constructor that allows use in trusted contexts,
13    // but only internal to the package
14    public MyClass (Boolean bypassFLS) {
15        this.bypassFLS = bypassFLS;
16    }
17    @namespaceAccessible
18    protected Boolean getBypassFLS() {
19       return bypassFLS;
20    }
21}

Versioned Behavior Changes

In API version 47.0 and later, @NamespaceAccessible is not allowed on an entity marked with @AuraEnabled. Therefore, an Aura or Lightning web component installed from a package can’t call an Apex method from another package, even if both packages are in the same namespace.

In API version 50.0 and later:
  • Apex variables or methods that are public or protected and annotated with @namespaceAccessible must be in a public class with the @namespaceAccessible annotation.
  • Apex inner classes that are public or protected and annotated with @namespaceAccessible must be enclosed in a public outer class with the @namespaceAccessible annotation.