Several common methods of java objects to Java String

zhaozj2021-02-16  171

• In the actual development and application of Java projects, it is often necessary to use the object to convert the object to String. This article will summarize the commonly used conversion methods. Common methods have object # toString (), (String) to convert objects, String.Valueof (Object), etc. These methods are analyzed by one by one below.

Method 1: Using Object # toString () method

Please see the example below: ??? Object object = getObject (); system.out.println (Object.toString ()); in this method of use, because there is already a public method in java.lang.Object class. Tostring (), This method can be called for any Java object in any strict sense. But when you use, you must ensure that Object is not a null value, otherwise the NullPointerexception will throw an exception. When using this method, it is usually derived to override the toString () method in the object of Object.

Method 2: Type conversion (String) Object method

This is the standard type conversion, converts Object to the value of the String type. When using this method, it is necessary to note that the type must be able to convert a string type. Therefore, it is best to use instanceof to make a type check to determine if it can be converted. Otherwise it is easy to throw the CalssCastException exception. In addition, it is necessary to be particularly careful because objects defined as an Object type are syntax checking and not reporting an error, which may cause potential errors. Be careful at this time. Such as: Object obj = new integer (100); string? Strval = (string) OBJ; it will be wrong at runtime because the Integer type is forced to convert to a String type, and cannot be passed. However, Integer Obj = new integer (100); string? Str remote = (string) OBJ; if it is formatted, the syntax error will be reported. In addition, because NULL values ​​can be forced to convert to any Java class type, (String) NULL is also legal.

Method 3: Using String.Valueof (Object)

String.Valueof (Object) The foundation is Object # toString (). But it is different from Object # toString (). In the analysis of the front method 1, it is not necessary to ensure that the latter is not NULL. However, when using the third approach, you will not have to worry about whether Object is a null value. To facilitate the problem, let's analyze the relevant source code. JDK String # valueof (Object) source code as follows: ??? / ** ???? * returns the string representation of the object argument. ???? * ???? * @Param ?? Obj ?? an Object . ???? * @return? if the argument is null, the a string equal to ???? * ????????? "null"; otherwise, the value of ???? * ?? ??????? obj.to taster () is returned. ???? * @see ???? java.lang.object # toString () ???? * / ??? public static string valueof (Object Obj) {

转载请注明原文地址:https://www.9cbs.com/read-9011.html

New Post(0)