Flat Preloader Icon

Java Reflection

Overview

  • What is Java Reflection?
  • Class Object
  • Constructors
  • Fields
  • Methods
  • Annotations

What Is Java Reflection?

  • Powerful and helpful feature which helps to inspect the classes, interfaces, methods etc, at runtime without knowing about these at compile time.
  • E.g. Methods[] m = testObject.getClass().getMethods()

Class Object

  • JVM creates a class object for all the objects of that class.
  • It is shared by all these objects.
  • E.g. Class test= testObject.class;
  • Or one can use Class.forName(String);
  • From the class, we can get the information about class name, modifiers, package information, superclass, constructors, methods, fields and annotations.

Constructors

  • Public Constructors for a class could be obtained by
    Constructor[] c = myClass.getConstructors();
  • A constructor with specific type of parameter can be obtained by
    Constructor constructor =testClass.getConstructor(new Class[] {String.class})
  • A new object could be created using these constructors.
java.lang.reflect Package: Reflection in Java is primarily implemented through the java.lang.reflect package, which contains classes like Class, Method, Field, Constructor, etc., that provide the necessary methods and APIs for reflective operations.

Fields

  • We can get all public fields of the object by
    : Field[] f = myClass.getFields();
  • All fields including private ones could be accessed by
    Field[] f = myClass.getDeclaredFields();
  • A particular field could be accessed by
    Field f = myClass.getField(“fieldName”);
  • For accessing and setting values on fields, we can use
    • f.getValue(Object);
    • f.set(Object, Object);

Methods

  • We can get all public methods of the object by :
    Method[] m = myClass.getMethods();
  • All methods including private ones could be accessed by
    Method[] m = myClass.getDeclaredMethods();
  • A particular method could be accessed by
    Method m = myClass.getMethod(“methodName”, Class parameters);
  • For invoking a method, we can use
    m.invoke(Object, Object);

Annotations

  • We can access the annotations defined at object, method, field and parameter level.
  • @Retention:- This property should be set as RetentionPolicy.RUNTIME for accessing it using reflection.
  • E.g. Annotation[] a= myClass.getAnnotations()