简体   繁体   中英

Are there any constants for Java Mail standard properties? Is there any other way for ide/compiler to check their spelling?

All examples of Java Mail usage that I've found set properties for Session with property names defined as simple strings. Example:

   props.put("mail.smtp.auth", "true");
   props.put("mail.smtp.starttls.enable", "true");

As soon as documentation defines "standard" properties for Java Mail API, there might exist a way to check their correctness and autocomplete them in IDE.

However, I can't find such way using google/documentation. I also can't find any explanation for absence of predefined names.

So, is there any way to overcome this problem? Am I missing something obvious that makes an approach with constants impossible/unwanted?

No, there are no defined constants for these properties. Part of the reason why is that these properties are not completely constant - they're composed of some constant parts but also include the name of the protocol. The JavaMail reference implementation includes at least 8 protocols, so there would need to be 8 "constants" for each property. The property name needs to match the protocol that you're using; I don't know how an IDE would figure that out.

I was also looking for similar API's. And it is true that Java does not provide API for email constants however I came across these email API's from apache which provide EmailConstants class for this use.

I suggest to create an interface for this:

public interface SessionProperties {
    String AUTH = "mail.smtp.auth";
}

An interface makes it easy to define and use the names (just implement the interface to get access). This was most useful with older Java versions where you had no static imports.

Note that some people frown upon this . The main reason why I'm still using it is the simplicity of the code: I don't have to write all those access modifiers.

From my experience, there are several reasons why many frameworks forget to define global constants for things like that:

  1. Misunderstood data hiding (the constants are somewhere in the code but private - great, they are part of the public API but private! Well done...)

  2. People love cut&paste code. That's what they started with and they always fall back to it.

  3. It makes examples easier to share since all the information is there.

  4. People are too lazy to create a proper public API.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM