The Class Class
The last method of
Object we need to discuss is getClass( )
. This method returns a reference to the
Class object that produced the
Object instance.
A good measure of the complexity of an object-oriented language is
the degree of abstraction of its class structures. We know that every
object in Java is an instance of a class, but what exactly is a
class? In C++, objects are formulated by and instantiated from
classes, but classes are really just artifacts of the compiler. Thus,
you see classes only mentioned in C++ source code, not at runtime. By
comparison, classes in Smalltalk are real, runtime entities in the
language that are themselves described by “metaclasses”
and “metaclass classes.” Java strikes a happy medium
between these two languages with what is effectively a two-tiered
system that uses Class objects.
Classes in Java source code are represented at runtime by instances
of the java.lang.Class class. There’s a
Class object for every class you use; this
Class object is responsible for producing
instances for its class. You don’t have to worry about any of
this unless you are interested in loading new kinds of classes
dynamically at runtime. The Class object is also
the basis for “reflecting” on a class to find out its
methods and other properties; we’ll discuss this feature in the
next section.
We get the Class associated with a particular
object with the getClass( ) method:
String myString = "Foo!" Class c = myString.getClass( );
We can also get the Class ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access