2017-10-12 39 views
2

這個問題涉及(但不重複)Why does compilation of public APIs leaking internal types not fail?如何在導出的API中聲明內部方法?

一個如何定義枚舉的方法是從內部類只訪問?

具體來說:

  • 用戶需要能夠通過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引用非出口型。有一個更好的方法嗎?

回答