为什么 JavaMail Transport.send() 是静态方法?
我正在修改我没有编写的使用 JavaMail 的代码,并且在理解为什么 JavaMail API 是这样设计的方面遇到了一些困难。我有一种感觉,如果我理解的话,我可以做得更好。
我们调用:
transport = session.getTransport("smtp");
transport.connect(hostName, port, user, password);
那么为什么 Eclipse 警告我 this:
transport.send(message, message.getAllRecipients());
is a call to a static method?
如果我无法使用 Transport 对象发送消息,为什么我要获取 Transport 对象并提供特定于它的设置? Transport 类如何知道使用什么服务器和其他设置来发送消息?它运行良好,这令人难以置信。如果我为两个不同的服务器实例化 Transport 对象会怎样?它怎么知道该使用哪一个?
在写这个问题的过程中,我发现我真的应该调用:
transport.sendMessage(message, message.getAllRecipients());
那么静态 Transport.send() 方法的目的是什么?这只是糟糕的设计,还是有原因?
I'm revising code I did not write that uses JavaMail, and having a little trouble understanding why the JavaMail API is designed the way it is. I have the feeling that if I understood, I could be doing a better job.
We call:
transport = session.getTransport("smtp");
transport.connect(hostName, port, user, password);
So why is Eclipse warning me that this:
transport.send(message, message.getAllRecipients());
is a call to a static method?
Why am I getting a Transport object and providing settings that are specific to it if I can't use that object to send the message? How does the Transport class even know what server and other settings to use to send the message? It's working fine, which is hard to believe. What if I had instantiated Transport objects for two different servers; how would it know which one to use?
In the course of writing this question, I've discovered that I should really be calling:
transport.sendMessage(message, message.getAllRecipients());
So what is the purpose of the static Transport.send() method? Is this just poor design, or is there a reason it is this way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Transport.send()
基本上是一种便捷方法。是的,如果您管理自己的Transport
实例,请调用sendMessage()
。我不确定我是否认为这是糟糕的设计,因为您经常不关心管理发送和监控传输的细节。破解
send()
方法,看看它能为您做什么。命名或放置此方法的其他方式可能会稍微好一些。Transport.send()
is basically a convenience method. Yes, if you're managing your ownTransport
instance, callsendMessage()
.I'm not sure I consider it bad design, since frequently you don't care to manage the details of sending and monitoring transport. Crack open the
send()
method to see what it does for you. Other ways of naming or placing this method could be marginally better.javadoc 说:
Send 是一个静态方法,它创建并管理自己的连接。与用于调用此方法的任何 Transport 实例关联的任何连接都将被忽略且不被使用。此方法只能使用 Transport.send(msg); 形式调用,并且永远不应该使用实例变量调用。
是的,设计可能不好
The javadoc says:
Send is a static method that creates and manages its own connection. Any connection associated with any Transport instance used to invoke this method is ignored and not used. This method should only be invoked using the form Transport.send(msg);, and should never be invoked using an instance variable.
And yes probably, the design is not good