此问题与(但不重复)
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引用了非导出类型。有更好的方法吗?