Java - Reflection Java Reflection

Introduction

The reflection in Java is provided through the reflection API in the java.lang.reflect package.

Some of the frequently used classes in reflection are listed in the following table.

Class Name
Description
java.lang.Class

represents a single class loaded by a class loader in
the JVM.
java.lang.reflect.Field

represents a single field of a class or an interface.
The field represented by this object may be a static field or an instance field.
java.lang.reflect.Constructor
represents a single constructor of a class.
java.lang.reflect.Method


represents a method of a class or an interface.
The method represented by this object may be a class method or an instance
method.
java.lang.reflect.Modifier

used to decode the access modifiers for
a class and its members.
java.lang.reflect.Array
used to create arrays at runtime.

By using Java reflection you can

  • find out the class name of the object.
  • get the class package name, its access modifiers, etc.
  • find out the methods defined in the class, their return type, access modifiers, parameters type, parameter names, etc.
  • find out all field of the class.
  • find out all constructors defined in the class.
  • create an object of the class using one of its constructors.
  • invoke its method knowing just the method's name and method's parameter types.
  • get or set the state of an object at runtime.
  • create an array of a type dynamically at runtime and manipulate its elements.

Related Topics