Java Reference
In-Depth Information
This will produce the same output as before.
Remember that the Class object returns the actual class of an object. Suppose you define a String object
like this:
String saying = "A stitch in time saves nine.";
You could store a reference to this String object as type Object :
Object str = saying;
The following statement displays the type of str :
System.out.println(str.getClass().getName());
This statement outputs the type name as java.lang.String . The fact that the reference is stored in a
variable of type Object does not affect the underlying type of the object itself.
When your program is executing, there are instances of the Class class in existence that represent each
of the classes and interfaces in your program (I explain what an interface type is a little later in this chapter).
There is also a Class object for each array type in your program as well as every primitive type. The Java
Virtual Machine (JVM) generates these when your program is loaded. Because Class is primarily intended
for use by the JVM, it has no public constructors, so you can't create objects of type Class yourself.
Although you can use the getClass() method to get the Class object corresponding to a particular class
or interface type, there is a more direct way. If you append .class to the name of any class, interface, or
primitive type, you have a reference to the Class object for that class.
For example, java.lang.String.class references the Class object for the String class and
Duck.class references the Class object for the Duck class. Similarly, int.class is the class object for the
primitive type, int , and double.class is the one corresponding to type double . This may not seem par-
ticularly relevant at this point, but keep it in mind. Since there is only one Class object for each class or
interface type, you can test for the class of an object programmatically. Given a variable pet of type Animal ,
you could check whether the object referenced was of type Duck with the following statement:
if(pet.getClass() == Duck.class) {
System.out.println("By George - it is a duck!");
}
This tests whether the object referenced by pet is of type Duck . Because each Class object is unique,
this is a precise test. If pet contained a reference to an object that was a subclass of Duck , the result of the
comparison in the if would be false . You see a little later in this chapter that you have an operator in Java,
instanceof , that does almost the same thing — but not quite.
Note that the Class class is not an ordinary class. It is an example of a generic type . I discuss generic
types in detail in Chapter 13, but for now, be aware that Class really defines a set of classes. Each class,
interface, array type, and primitive type that you use in your program is represented by an object of a unique
class from the set defined by the Class generic type.
Duplicating Objects
Search WWH ::




Custom Search