2

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...

4

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(){
        //...
    }
}
  • Exactly what I was looking for! do you know if an unlocked package can reference an @namespaceAccessible managed class in a managed package? – NSjonas May 22 at 15:27
  • @NSjonas I haven't tried it by myself yet, but according to the documentation, it should work, if the unlocked package has the same namespace. – Oleksandr Berehovskyi May 22 at 15:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.