|
|
Examining Classes |
You can retrieve aClassobject in several ways:
- If an instance of the class is available, you can invoke
Object.getClass. ThegetClassmethod is useful in situations when you want to examine an object, but you don't know its class. The following line of code gets theClassobject for an object namedmystery:Class c = mystery.getClass();- If you want to retrieve the
Classobject for the superclass that anotherClassobject reflects, invoke thegetSuperClassmethod. In the following example,getSuperClassreturns theClassobject associated with the theTextComponentclass, becauseTextComponentis 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
Classobject by appending.classto its name. In the next example, theClassobject that represents theButtonclass is retrieved:Class c = java.awt.Button.class;- If the class name is unknown at compile time, but available at run time, you can use the
forNamemethod. In the following example, if theStringnamedstrgis set to "java.awt.Button" thenforNamereturns theClassobject associated with theButtonclass:Class c = Class.forName(strg);
|
|
Examining Classes |