Java Tutorial - Java Script : Inspecting Classes and Methods with Reflection

Java Tutorial - Java Script :

Inspecting Classes and Methods with Reflection

You also can create Class objects by using the forName() class method with a single argument: a string containing the name of an existing class. The following statement creates a Class object representing a JLabel, one of the classes of the javax.swing package:
Class lab = Class.forName(“javax.swing.JLabel”);
The forName() method throws a ClassNotFoundException if the specified class cannot be found, so you must call forName() within a try-catch block or handle it in some other manner. To retrieve a string containing the name of a class represented by a Class object, call getName() on that object. For classes and interfaces, this name includes the name of the class and a reference to the package to which it belongs. For primitive types, the name corresponds to the type’s name (such as int, float, or double).
Class objects that represent arrays are handled a little differently when getName() is called on them. The name begins with one left bracket character (“[“) for each dimension of the array; float[] would begin with “[“, int[][] with “[[“, KeyClass[][][] with “[[[“, and so on. If the array is of a primitive type, the next part of the name is a single character representing the type, as shown in Table 16.1.
For arrays of objects, the brackets are followed by an L and the name of the class. For example, if you called getName() on a String[][] array, the result would be [[Ljava.lang.String. You also can use the Class class to create new objects. Call the newInstance() method on a Class object to create the object and cast it to the correct class. For example, if you have a Class object named thr that represents the Throwable interface, you can create a new object as follows: Throwable thr2 = (Throwable)thr.newInstance(); The newInstance() method throws several kinds of exceptions:
·         IllegalAccessException—You do not have access to the class either because it is not public or because it belongs to a different package.
·         InstantiationException—You cannot create a new object because the class is abstract.
·         SecurityViolation—You do not have permission to create an object of this class.
When newInstance() is called and no exceptions are thrown, the new object is created by calling the constructor of the corresponding class with no arguments.