Java Reflection - Class


The entry point for all reflection operations is java.lang.Class. There are several ways to get a Class depending on whether the code has access to an object, the name of class, a type, or an existing Class.
To get the class of an object - the class that is instantiated by the given object, you can use the method getClass()
Class c = object.getClass();
For any given class that is defined in the code, you can get the class object by accessing the field class. For example:
Class c = java.util.Date.class
If you have the name of the class in a String, you can get the corresponding Class object by using Class.forName() method. For example
String s = "java.util.Date";
Class c = Class.forName(s);
The class Class is quite rich and provides several useful methods for working with the Class objects.

Important Methods

Some of the common methods are listed here.
getSuperclass()Returns the super class for the given class.
getClasses()Returns all the public classes, interfaces, and enums that are members of the class including inherited members.
getDeclaredClasses()Returns all of the classes interfaces, and enums that are explicitly declared in this class.
getDeclaringClass()Returns the Class in which the class was declared. Anonymous Class Declarations will not have a declaring class but will have an enclosing class.
getEnclosingClass()Returns the immediately enclosing class of the class.
getDeclaredField(String name)Pick one field by name
getField(String name)Pick one field by name
getDeclaredFields()Get an array of Fields
getFields()Get an array of Fields