代码之家  ›  专栏  ›  技术社区  ›  Gili

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

  •  2
  • Gili  · 技术社区  · 7 年前

    此问题与(但不重复) Why does compilation of public APIs leaking internal types not fail?

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

    明确地:

    • 用户需要能够通过 enum API其他部分的值。
    • 枚举 用户传递的值,内部类需要调用不同的操作。
    • 确保每个 枚举 值映射到一个操作,我们在 枚举 .

    启示:

    • 这个 必须是 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 回复  |  直到 7 年前
        1
  •  0
  •   Gili    7 年前

    艾伦·贝特曼 pointed out shared secret mechanism JDK使用。这允许内部类跨包共享包保护的方法,而无需使用反射。