Getting a Class Object


MyClass a = new MyClass(); a.getClass();



The most basic thing you usually do when doing reflective programming is to get a Class object. Once you have a Class object instance, you can obtain all sorts of information about the class and even manipulate the class. In this phrase, we use the getClass() method to get a Class object. This method of getting a Class object is often useful in situations in which you have the object instance but do not know what class it is an instance of.

There are several other ways of obtaining a Class object. If you have a class for which the type name is known at compile time, there is an even easier way of getting a class instance. You simply use the compiler keyword .class, as shown here:

Class aclass = String.class;


If the class name is not known at compile time, but is available at runtime, you can use the forName() method to obtain a Class object. For example, the following line of code will create a Class object associated with the java.lang.Thread class.

Class c = Class.forName("java.lang.Thread");


You can also use the getSuperClass() method on a Class object to obtain a Class object representing the superclass of the reflected class. For example, in the following code, Class object a reflects the TextField class, and Class object b reflects the TextComponent class because TextComponent is the superclass of TextField.

TextField textField = new TextField(); Class a = textField.getClass(); Class b = a.getSuperclass();





JavaT Phrasebook. Essential Code and Commands
Java Phrasebook
ISBN: 0672329077
EAN: 2147483647
Year: 2004
Pages: 166

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net