Chapter 7
[ 163 ]
try {
Class iClazz = Class.forName("java.lang.Integer");
Field[] fields = iClazz.getDeclaredFields();
System.out.println("All fields of Integer class:");
for(int i = 0; i < fields.length;i++)
System.out.println(" " + fields[i].getName());
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
We can access the Class object from an instance by calling its Object.getClass()
method. If we don't have an instance of the class to hand, we can get the Class object
by using .class after the class name, for example, String.class. Alternatively, we
can call the static Class.forName, passing to it a fully qualified class name.
Class has numerous methods, such as getPackage(), getMethods(), and
getDeclaredFields() that allow us to interrogate the Class object for details about
the Java class under inspection. The preceding example will output various details
about String, Integer, and Double: