如何在导出的 API 中声明内部方法?
How to declare internal methods in exported APIs?
此问题与
有关(但不重复)
如何定义只能从内部访问的枚举方法 类?
具体来说:
- 用户需要能够将
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 引用了非导出类型。有更好的方法吗?
Alan Bateman pointed out a 被 JDK 使用。这允许内部 类 跨包共享受包保护的方法,而无需诉诸反射。
此问题与
如何定义只能从内部访问的枚举方法 类?
具体来说:
- 用户需要能够将
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 引用了非导出类型。有更好的方法吗?
Alan Bateman pointed out a