Home > Java > Java Tutorial > body text

详解java 中valueOf方法实例

零下一度
Release: 2017-05-25 14:52:18
Original
2580 people have browsed it

case1:Object 对象转String

需要强调的是String.valueOf()方法,当参数为类型是object,且值时null的时候他的处理方式

    public 
static
 String valueOf(Object obj) {
        
return
 (obj == null) ? "null" : obj.toString();
    }
Copy after login

     这样在后面的成都不会报错但是在逻辑上可能出错,一般习惯写的是str!=null && str.length()>0,当是由 str = String.valueOf(obj)得到时上面的额判断条件就有问题了

所以遇到 Object 对象转String 最好强转 str=  (String) obj此时,当obj为null时,str依然为null,case2:Object 装基本类型的包装类型,(关注integer和Long,Double)

     首先 obj被赋值之后 obj还是属于数据所属基本类型的包装类型可以通过instanceOf 判断知道.

所以直接用强转就可以,没有必要用类似Long.ParseLong(String.valueOf(obj))这类方法,用这中复杂的问题会有一个问题就是不能返回值不能包含null

如果是null就直接抛出异常了,因为在String.valueOf()方法时已经把null转为字符串了,而Long.parseLong()方法如果传入了null字符串就会报异常,

Long.ParseLong(String.valueOf(obj)) 方法就等价与 (long)obj,用基本类型去强转

       更好的做法是用(Long)obj去强转,在后面的程序中做null情况的判断和处理

case3: 基本类型的包装类型和String的vlaueOf方法对与obj=null的处理是不一样的,String.valueOf(obj)的处理返回的"null"字符串,而基本类型的包装类型返回的null

强调一下,String不是基本类型,更不是基本包装类型

总结:

1遇到obj类型转string时最好强转

2遇到obj类型转几倍类型的包装类型时最好强转,如果需要可以先用instanceOf判断其类型时再强转

相关推荐】

 1. Java中valueOf,parseInt,toString三者的区别

2. Java中valueOf和toString,(String)之间的区别

3. tostring()和valueof()的用法及两者的区别

4. valueOf函数与toString方法深入理解

5. object转换函数toString()与valueOf()介绍

6. JavaScript中用toString()方法返回时间为字符串

The above is the detailed content of 详解java 中valueOf方法实例. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact [email protected]
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!