Properties获取属性为 null 的原因以及注意点

开发了一个发邮件的功能,发现配置的 mail.debug 不好使。
Properties properties = new Properties();
properties.set(“mail.debug”,true)

后来经过调试,发现java mail 调用此处使用的为


   // Constructor is not public
    private Session(Properties props, Authenticator authenticator) {
	this.props = props;
	this.authenticator = authenticator;

	if (Boolean.valueOf(props.getProperty("mail.debug")).booleanValue())
	    debug = true;

	initLogger();
	logger.log(Level.CONFIG, "JavaMail version {0}", Version.version);

使用的为 getProperty 此时获取为null

getProperty源码:

 /**
     * Searches for the property with the specified key in this property list.
     * If the key is not found in this property list, the default property list,
     * and its defaults, recursively, are then checked. The method returns
     * {@code null} if the property is not found.
     *
     * @param   key   the property key.
     * @return  the value in this property list with the specified key value.
     * @see     #setProperty
     * @see     #defaults
     */
    public String getProperty(String key) {
        Object oval = super.get(key);
        String sval = (oval instanceof String) ? (String)oval : null;
        return ((sval == null) && (defaults != null)) ? defaults.getProperty(key) : sval;
    }

如果发现取到的类型不为 String,则返回 null。
自此,坑已明白,因为继承于Hashtable 可以使用很多 Hashtable 的方法,导致没有注意其对类型的要求。

* @author  Arthur van Hoff
 * @author  Michael McCloskey
 * @author  Xueming Shen
 * @since   JDK1.0
 */
public
class Properties extends Hashtable<Object,Object> {
    /**
     * use serialVersionUID from JDK 1.1.X for interoperability
     */

注意点:
后续使用Properties 推荐以下置入值

properties.setProperty("key","value");

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值