Java Reference
In-Depth Information
// You need to AND the returned value from the getModifiers() method with
// appropriate value returned from xxxModifiers() method of the Modifiers class
int mod = c.getModifiers() & Modifier.classModifiers();
String modifiers = Modifier.toString(mod);
It is straightforward to get the name of the superclass of a class. Use the getSuperclass() method of the Class
class to get the reference of the superclass. Note that every class in Java has a superclass except the Object class. If the
getSuperclass() method is invoked on the Object class, it returns null . Therefore, it is important that you check the
returned value of the getSuperclass() method for null reference before you try to use it to get its name. This check is
removed below for clarity. However, the code for the ClassReflection class has this check:
Class superClass = c.getSuperclass();
if (superClass != null) {
String superClassName = superClass.getSimpleName();
}
the getSuperclass() method of the Class class returns null when it represents the Object class, a class for an
interface such as List.class , and a class for a primitive type such as int.class , void.class , etc.
Tip
To get the names of all interfaces implemented by a class, you use the getInterfaces() method of the Class
class. It returns an array of Class object. Each element in the array represents an interface implemented by the class.
To get the list of all interfaces, you need to loop through all the elements of this array. The ClassReflection class has
a getClassInterfaces() method that returns all interfaces implemented by a Class object separated by a comma.
// Get all interfaces implemented by c
Class[] interfaces = c.getInterfaces();
The getClassDescription() method of the ClassReflection class puts all parts of a class declaration into a
string and returns that string. The main() method of this class demonstrates how to use this class.
Java 8 added a method called toGenericString() to the Class class that returns a string describing the
class. the string contains the modifiers and type parameters for the class. the call Person.class.toGenericString()
will return public class com.jdojo.reflection.Person .
Note
Reflecting on Fields
A field of a class is represented by an object of the java.lang.reflect.Field class. The following four methods in the
Class class can be used to get information about the fields of a class:
Field[] getFields()
Field[] getDeclaredFields()
Field getField(String name)
Field getDeclaredField(String name)
 
 
Search WWH ::




Custom Search