如何在导出的API中声明内部方法?

时间:2017-10-12 04:41:34

标签: java java-module

此问题与Why does compilation of public APIs leaking internal types not fail?

有关(但不重复)

如何定义只能从内部类访问的枚举方法?

具体做法是:

  • 用户需要能够将enum值传递给API的其他部分。
  • 根据用户传递的enum值,内部类需要调用不同的操作。
  • 为了确保每个enum值都映射到一个操作,我们在enum中声明了一个方法。

意义:

  • enum必须为public并已导出。
  • 内部类必须位于与enum不同的包中,以防止它们被导出。
  • enum方法必须为public,内部类才能调用它。

我想到阻止用户调用public方法的唯一方法是让它引用一个非导出类型。例如:

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);
}

不幸的是,当我这样做时,编译器会抱怨导出的API引用了非导出类型。有更好的方法吗?

1 个答案:

答案 0 :(得分:0)

Alan Bateman pointed out使用JDK使用的shared secret mechanism。这允许内部类跨包共享受包保护的方法,而无需使用反射。

相关问题