Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
You can retrieve aClass
object in several ways:
- If an instance of the class is available, you can invoke
Object.getClass
. ThegetClass
method is useful when you want to examine an object but you don't know its class. The following line of code gets theClass
object for an object namedmystery
:Class c = mystery.getClass();- If you want to retrieve the
Class
object for the superclass that anotherClass
object reflects, invoke thegetSuperclass
method. In the following example,getSuperclass
returns theClass
object associated with the theTextComponent
class, becauseTextComponent
is the superclass ofTextField
:TextField t = new TextField(); Class c = t.getClass(); Class s = c.getSuperclass();- If you know the name of the class at compile time, you can retrieve its
Class
object by appending.class
to its name. In the next example, theClass
object that represents theButton
class is retrieved:Class c = java.awt.Button.class;- If the class name is unknown at compile time, but available at runtime, you can use the
forName
method. In the following example, if theString
namedstrg
is set to "java.awt.Button" thenforName
returns theClass
object associated with theButton
class:Class c = Class.forName(strg);
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
Copyright 1995-2004 Sun Microsystems, Inc. All rights reserved.