Java String.valueOf()方法——出你意料的"null"字符串

本文详细解析了Java中String.valueOf()方法的使用细节,特别是当参数为null时的行为差异及可能引发的问题,并提供了如何正确判断返回值的建议。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

      String.valueOf()方法当传入的参数为一个引用且该引用引用的是null时,方法返回字符串"null",此时若用StringUtils.isBlank()这类方法判断时将返回true,因为此时调用的valueOf(Object obj)方法,该方法的源码如下(jdk1.8.0_131中String的部分源码):
/**
     * Returns the string representation of the {@code Object} argument.
     *
     * @param   obj   an {@code Object}.
     * @return  if the argument is {@code null}, then a string equal to
     *          {@code "null"}; otherwise, the value of
     *          {@code obj.toString()} is returned.
     * @see     java.lang.Object#toString()
     */
    public static String valueOf(Object obj) {
        return (obj == null) ? "null" : obj.toString();
    }

      调用String.valueOf()时若实参直接写为null,方法会报NPE,通过IDE可以看出,valueOf(null)调用的String类的方法如下(jdk1.8.0_131中String的部分源码):

/**
     * Returns the string representation of the {@code char} array
     * argument. The contents of the character array are copied; subsequent
     * modification of the character array does not affect the returned
     * string.
     *
     * @param   data     the character array.
     * @return  a {@code String} that contains the characters of the
     *          character array.
     */
    public static String valueOf(char data[]) {
        return new String(data);
    }
      而上述源码的中new String(data)又会调用如下方法(jdk1.8.0_131中String的部分源码):
/**
     * Allocates a new {@code String} so that it represents the sequence of
     * characters currently contained in the character array argument. The
     * contents of the character array are copied; subsequent modification of
     * the character array does not affect the newly created string.
     *
     * @param  value
     *         The initial value of the string
     */
    public String(char value[]) {
        this.value = Arrays.copyOf(value, value.length); //value[]为null时,报NPE
    }
      鉴于valueOf()可能会返回"null"字符串,使用时要特别注意,不能再用StringUtils.isEmpty()或isBlank()来简单地判断valueOf()返回值是否为空了。
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值