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 theenum
.
Implications:
- The
enum
must bepublic
and exported. - The internal classes must reside in a separate package than the
enum
to prevent them from getting exported. - The
enum
method must bepublic
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?