You can retrieve a
Class
object in several ways:- Using getClass methodIf an instance of the class is available, you can invoke
Object.getClass
. ThegetClass
method is useful in situations 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();
- Using .class if you know the name of the class at compile timeIf 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:
i.e. Class c = ClassName.class;Class c = java.awt.Button.class;
- Using forName()
If the class name is unknown at compile time, but available at run time, you can use theforName
method. In the following example, if theString
namedstrg
is set to "java.awt.Button" thenforName
returns theClass
object associated with theButton
class:
It is possible that class we are fetching at runtime does not exist, so we have to catch ClassNotFoundException.Class c = Class.forName(strg);
No comments:
Post a Comment