Stick with the 'instanceof' operator
Personally, I always use instanceof to check object type, rather than use .getClass() - .getClass() is not as flexible:
Code:
public class Explanation2 {
public static void main(String[] args) {
String s = new String("Hello");
Object o = new Object();
// Is 's' of type 'String'? (Note - I don't say ", or a subclass of")
if (s.getClass() == String.class) {
System.out.println("'s' is of the String class. It is of type: " + s.getClass().getName());
}
// Is 's' of type 'Object'? (Note - I don't say ", or a subclass of")
if (s.getClass() == Object.class) {
System.out.println("Will never print out");
}
else {
System.out.println("'s' is NOT of the Object class. It is of type: " + s.getClass().getName());
}
System.out.println();
// Is 'o' of type 'Object'? (Note - I don't say ", or a subclass of")
if (o.getClass() == Object.class) {
System.out.println("'o' is of the Object class. It is of type: " + o.getClass().getName());
}
// Is 's' of type 'String'? (Note - I don't say ", or a subclass of")
if (o.getClass() == String.class) {
System.out.println("Will never print out");
}
else {
System.out.println("'o' is NOT of the String class. It is of type: " + o.getClass().getName());
}
System.out.println();
System.out.println("Assigning 'o' to the object referenced by 's'");
System.out.println();
o = s;
// Is 'o' of type 'String'? (Note - I don't say ", or a subclass of")
if (o.getClass() == String.class) {
System.out.println("'o' is of the String class. It is of type: " + o.getClass().getName());
}
// Is 's' of type 'Object'? (Note - I don't say ", or a subclass of")
if (o.getClass() == Object.class) {
System.out.println("Will never print out");
}
else {
System.out.println("'o' is NOT of the Object class. It is of type: " + o.getClass().getName());
}
}
}
This will produce:
Code:
C:\david\docs\forums\instance_test>javac Explanation2.java
C:\david\docs\forums\instance_test>java Explanation2
's' is of the String class. It is of type: java.lang.String
's' is NOT of the Object class. It is of type: java.lang.String
'o' is of the Object class. It is of type: java.lang.Object
'o' is NOT of the String class. It is of type: java.lang.Object
Assigning 'o' to the object referenced by 's'
'o' is of the String class. It is of type: java.lang.String
'o' is NOT of the Object class. It is of type: java.lang.String