[SalesForce] Accessing public class from different Package in same Namespace

Supposedly, it now should be possible to access a public class from different packages within the same namespace:

Multiple packages per namespace, so you can better organize your source and easily share Apex code. You can use public Apex classes across packages rather than global Apex classes.

However, when I try to do this in practice, I get an error when I create the package:version for the dependent package:

Class MyNamespace.MyClass : Type is not visible: MyNamespace.MyPublicClass,MyClass: Type is not visible: MyNamespace.MyPublicClass

Classes look like this:

// in package-with-dependent
global class MyClass{
   //...

   global string foo(){
      MyNamespace.MyPublicClass pc = new MyNamespace.MyPublicClass();
   }
}
// package-with-public
public class MyPublicClass{
   public MyPublicClass(){
     //...
   }

}

My Package json looks like this:

"packageDirectories": [
    {
        "path": "package-with-dependent",
        "package": "package-with-dependent",
        "versionName": "ver 0.1",
        "versionNumber": "0.1.0.NEXT",
        "default": true,
        "dependencies": [
            {
                "package": "package-with-public",
                "versionNumber": "0.1.0.LATEST"
            }
        ]
    },
    {
        "path": "package-with-public",
        "package": "package-with-public",
        "versionName": "ver 0.1",
        "versionNumber": "0.1.0.NEXT",
        "default": false
    }
],
"namespace": "MyNamespace",

And I'm running force:package:version:create on the package with MyPublicClass first…

Has anyone actually had this work in practice? Any ideas why this might not be working? Documentation seems to be non-existent…

Best Answer

you forgot to use @namespaceAccessible annotation, in order to make public class accessible across different packages in one namespace. Here is a documentation

The @namespaceAccessible annotation marks public or protected Apex in a package as available to other packages with the same namespace. Unless explicitly annotated, Apex classes, methods, interfaces, and properties defined in a 2GP package aren’t accessible to other packages with which they share a namespace. There is no impact on Apex that isn’t packaged.


you want to have like the following

@namespaceAccessible
public class MyPublicClass{
    @namespaceAccessible
    public MyPublicClass(){
        //...
    }
}
Related Topic