2

This issue is related to (but not duplicated by) Why does compilation of public APIs leaking internal types not fail?

How can one define enum methods that are only accessible from internal classes?

Specifically:

  • Users need to be able to pass enum values to other parts of the API.
  • Depending on which enum value the user passed, internal classes need to invoke a different operation.
  • To ensure that each enum value is mapped to an operation, we declare a method in the enum.

Implications:

  • The enum must be public and exported.
  • The internal classes must reside in a separate package than the enum to prevent them from getting exported.
  • The enum method must be public for the internal classes to invoke it.

The only way I could think of preventing users from invoking the public method is have it reference a non-exported type. For example:

public enum Color
{
  RED
  {
    public void operation(NotExported ignore)
    {
      // ...
    }
  },
  GREEN,
  {
    public void operation(NotExported ignore)
    {
      // ...
    }
  },
  BLUE;
  {
    public void operation(NotExported ignore)
    {
      // ...
    }
  };

  /**
   * Carries out an internal operation.
   *
   * @param ignore prevent users from invoking this method
   */
  public abstract void operation(NotExported ignore);
}

Unfortunately, when I do that, the compiler complains that an exported API references a non-exported type. Is there a better way to do this?

Gili
  • 86,244
  • 97
  • 390
  • 689

1 Answers1

0

Alan Bateman pointed out a shared secret mechanism used by the JDK. This allows internal classes to share package-protected methods across packages without resorting to the use of reflection.

Gili
  • 86,244
  • 97
  • 390
  • 689