本文介绍了为什么Java类库仍然使用String常量来代替枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用几个Java类,例如和 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.debugtrue 属性实例。同样,如果您希望 MessageDigest 使用 SHA ,请创建 MessageDigest instance as

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 enums got introduced in Java 1.5. There's many more cases like that out there.

可扩展性

看看例如 MessageDigest 。 指定:

•MD5

•SHA-1

•SHA-256

• MD5
• SHA-1
• SHA-256

让其他库提供了与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.

同样可以允许其他实现以支持邮件会话属性的附加/自定义属性。

The same goes for allowing other javax.mail.Provider implementations to support additional/custom properties in the case of mail session properties.

这篇关于为什么Java类库仍然使用String常量来代替枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-16 04:20