Class Reflection and Introspection

This section provides a tutorial example on how to reflect a class as Class object and introspect its members: fields, methods, etc.

java.lang.Class also offers methods to support class reflection and introspection:

Here is tutorial example program showing you how to introspect a Java class:

 * Copyright (c) All Rights Reserved.
import java.lang.reflect.*;
class ClassReflection {
   public static void main(String[] a) { out = System.out;
      Class cls =;

      out.println("Class name:");
      out.println("   "+cls.getName());

      Class p = cls.getSuperclass();
      out.println("Parent class:");
      out.println("   "+p.getName());

      Constructor[] c  = cls.getDeclaredConstructors();
      for (int i = 0; i<c.length; i++)
         out.println("   "+c[i].toString());

      Field[] f  = cls.getDeclaredFields();
      for (int i = 0; i<f.length; i++)
         out.println("   "+f[i].toString());

      Method[] m  = cls.getDeclaredMethods();
      for (int i = 0; i<m.length; i++)
         out.println("   "+m[i].toString());

      Class[] s  = cls.getDeclaredClasses();
      out.println("Inner classes:");
      for (int i = 0; i<s.length; i++)
         out.println("   "+s[i].toString());

When executed, I got this result:

herong> java ClassReflection

Class name:
Parent class:
   private volatile boolean
   private final java.lang.Object
   public void throws java.i...
   public void[]) throws jav...
   public void[],int,int) th...
   public void throws
   public void throws
Inner classes:

The class reflection feature in Java can be useful to introspect any class by retrieving fields, methods and other members out of the class as reflection objects.

If you want to, you can actually invoke a class method as a reflection object using the Method.invoke() method.

Table of Contents

 About This Book

 JVM (Java Virtual Machine) Specification

 Java HotSpot VM - JVM by Oracle/Sun

 java.lang.Runtime Class - The JVM Instance

 java.lang.System Class - The Operating System

 ClassLoader Class - Class Loaders

Class Class - Class Reflections

 What Is java.lang.Class Class

 forName() Method - Loading Classes

Class Reflection and Introspection

 Array Class Introspection

 Invoking Methods of Class Instances

 JVM Runtime Data Areas

 JVM Stack, Frame and Stack Overflow

 Thread Testing Program and Result

 CPU Impact of Multi-Thread Applications

 I/O Impact of Multi-Thread Applications

 CDS (Class Data Sharing)

 Micro Benchmark Runner and JVM Options

 Micro Benchmark Tests on "int" Operations

 Micro Benchmark Tests on "long" Operations

 Micro Benchmark Tests in JIT Compilation Mode

 Micro Benchmark Tests on "float" and "double" Operations

 OpenJ9 by Eclipse Foundation

 JRockit JVM 28.2.7 by Oracle Corporation

 Archived Tutorials


 Full Version in PDF/EPUB