Java Reflection Introduction

Introduction

Reflection is the ability of software to analyze itself.

Java reflection is provided by the java.lang.reflect package and elements in java.lang.Class.

The package java.lang.reflect includes several interfaces.

ClassPrimary Function
AccessibleObjectbypass the default access control checks.
Array dynamically create and manipulate arrays.
Constructor Provides information about a constructor.
Executable An abstract superclass extended by Method and Constructor.
Field information about a field.
Methodinformation about a method.
Modifierinformation about class and member access modifiers.
Parameter information about parameters. (Added by JDK 8.)
Proxy Supports dynamic proxy classes.
ReflectPermission Allows reflection of private or protected members of a class.
// Demonstrate reflection.
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class Main {
  public static void main(String args[]) {
    try {/*from  w w  w  .  j ava2s  .  co  m*/
      Class<?> c = Class.forName("java.awt.Dimension");
      System.out.println("Constructors:");
      Constructor<?> constructors[] = c.getConstructors();
      for (int i = 0; i < constructors.length; i++) {
        System.out.println(" " + constructors[i]);
      }

      System.out.println("Fields:");
      Field fields[] = c.getFields();
      for (int i = 0; i < fields.length; i++) {
        System.out.println(" " + fields[i]);
      }

      System.out.println("Methods:");
      Method methods[] = c.getMethods();
      for (int i = 0; i < methods.length; i++) {
        System.out.println(" " + methods[i]);
      }
    } catch (Exception e) {
      System.out.println("Exception: " + e);
    }
  }
}



PreviousNext

Related