How can I tell if an object is convertible?
You can use the instanceof operator to determine whether an object can be converted to the specified type:
Object obj= "Hello";
if (obj instanceof String)
System.out.println ("obj object can be converted to a string ");
public class Ka{public static void Main (string[] args) {//Declare Hello when using the object class, then the compilation type of Hello is Object,object is the parent class of all classes// But the actual type of the hello variable is stringobject hello = "Hello";//string is a subclass of the object class, so it returns true. System.out.println ("Whether the string is an instance of the Object class:" + (hello instanceof Object));//returns TRUE. System.out.println ("String is an instance of a string class:" + (hello instanceof string));//returns FALSE. System.out.println ("String is an instance of the Math class:" + (hello instanceof Math)),//string implements the comparable interface, so returns TRUE. System.out.println ("String is an instance of the comparable interface:" + (hello instanceof comparable)); String a = "Hello"; the//string class is neither the math class nor the parent class of the math class, so the following code compilation cannot be passed//system.out.println ("string is an instance of the Math class:" + (a instanceof Math));}}
Line Result:
Whether the string is an instance of the Object class:True
Whether the string is an instance of the String class:True
Whether the string is an instance of the Math class:false
Whether the string is an instance of the comparable interface:true
Run:1
2
Experimental principle:
Declaration hello When using the object hello Span style= "font-family: the song Body;" > The compilation type is object , Span style= "font-family: ' Courier New ';" >object is the parent class of all classes, but hello string Span style= "font-family: the song Body;" string Yes object true (already converted).
1. This line of code System.out.println (" whether the string is an instance of the Object class:" + (hello instanceof Object)); return true (has already been converted).
2, but this line of code System.out.println (" string is an instance of a string class:" + (Hello instanceof String)); No conversions:
3. The /string class is neither the math class nor the parent class of the math class, so the following code compilation fails through //system.out.println (" whether the string is Math instances of the class: "+ (a instanceof Math));
The seventh chapter is how to tell if an object can be converted?