为什么Java类库仍然使用String常量来代替枚举 [英] Why does Java class library still use String constants in place of enum
问题描述
我正在使用几个Java类,例如 javax.Mail.Session
和 MessageDigest
。
I am using a few Java classes like javax.Mail.Session
and MessageDigest
for a tool I am building.
我注意到很难分配他们的属性,因为他们使用 String
常量。
I noticed that it was difficult assigning them properties because they were using String
constants for that.
例如,对于 Session
对象,您必须分配 String
code> property 实例中的键值对,然后用于创建会话
。因此,如果您希望会话记录调试消息,请将smtp.mail.debug
,true
属性
实例。同样,如果您希望 MessageDigest
使用 SHA
,请创建 MessageDigest
instance as MessageDigest.getInstance(SHA)
For example, for a Session
object, you have to assign String
key value pairs in a Property
instance which is then used to create a Session
. So if you want your session to log debugging messages, assign "smtp.mail.debug"
, "true"
in the Property
instance. Similarly, if you want your MessageDigest
to use SHA
, create the MessageDigest
instance as MessageDigest.getInstance("SHA")
我还没弄清楚该做什么如果说我想实现 MessageDigest
使用 MD5
/ RC4
等,或者添加另一个属性到我的会话
对象。
I am yet to figure out what to do and where to get the information if say I wanted to implement MessageDigest
using MD5
/ RC4
etc, or add another property to my Session
object.
如果公共枚举被这些各个类暴露以分配属性,那不是更好吗?
Wouldn't it be really better if public enums were exposed by these respective classes to assign properties ?
至少可以节省大量的搜索时间。
Would save programmers lot of searching time at least.
推荐答案
我可以看到两个主要原因:
I can see 2 main reasons:
向后兼容性
在Java 1.5中引入枚举
之前,给定已经是API的一部分。
The two examples you give were already part of the API before enum
s got introduced in Java 1.5. There's many more cases like that out there.
可扩展性
看看例如 MessageDigest
。 javadoc 指定:
Java平台的每个实现都需要支持标准MessageDigest算法的
:
Every implementation of the Java platform is required to support the following standard MessageDigest algorithms:
•MD5
•SHA-1
•SHA-256
• MD5
• SHA-1
• SHA-256
让其他 java.security.Provider
库提供了与API最不需要的其他算法相比的 MessageDigest
实现。在API级别上列出限制性枚举
中的默认值将限制可扩展性。
This lets other java.security.Provider
libraries provide MessageDigest
implementations for other algorithms than the ones minimally required by the API. Listing only the default ones in a restrictive enum
on the API level would limit extensibility.
同样可以允许其他 javax.mail.Provider
实现以支持邮件会话属性的附加/自定义属性。
The same goes for allowing other javax.mail.Provider
implementations to support additional/custom properties in the case of mail session properties.
这篇关于为什么Java类库仍然使用String常量来代替枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!