java - 如何在 Java 中强制指定常量

标签 java interface constants

我正在使用 JAX-RS 创建 REST Web 服务。

我需要使我的 Resource 类上的 @Path 注释的值可公开访问。使用反射来获取这个值似乎有点繁重。

我想我应该将值保存在 public static final String 中,以便 @Path 注释和其他类都可以访问它。

强制类提供此常量的最佳方法是什么?我的印象是,在接口(interface)中使用常量是一种反模式(Effective Java 第二版)。

编辑:

正如《Effective Java》所指出的,“如果常量与现有的类或接口(interface)紧密相关,则应该将它们添加到类或接口(interface)中”。

在我的情况下,@Path对于接口(interface)的所有实现者来说都是相同的,并且接口(interface)将提供方法,所以我认为我可以安全地将常量添加到接口(interface)中。

最佳答案

既然你已经有了 the book ,我给你引用一下(第98-99页):

If you want to export contants, there are several reasonable choices. If the constants are strongly tied to an existing class or interface, you should add them to the class or interface. For example, all of the boxed numerical primitive classes, such as Integer and Double, export MIN_VALUE and MAX_VALUE constants. If the constants are best viewed as members of an enumerated type, you should export them with an enum type. Otherwise, you should export the constants with a noninstantiable utility class.


但是,上面的答案涉及导出常量。如果你想“强制一个类提供这个常量”,那是另一回事,并且在你的接口(interface)中拥有常量并不能做到这一点。强制执行此类操作的唯一方法是在界面中为其提供 getter。

关于java - 如何在 Java 中强制指定常量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21333460/

相关文章:

java - 无法让 CSS 加载到网络应用程序中

java - 如何将参数传递给接口(interface)的一个实现者而不是其他实现者(不在构造函数中传递它)?

c++ - 我的 C++ 游戏架构

php - 可迭代对象的正确 phpdoc 注释?

c++ - const 基类的作用

java - 接口(interface)方法与类方法

java - Appium找不到 'adb.exe'

c - 如何在 C 中为文件扩展名定义 ".txt"常量?

java - Kotlin 术语 "mutable"错了吗?

java - 如何复制不包括目标为空的值的行?