SEARCH BY

All

  • All
  • Java8
  • Spring

Java Reflection API indepth

Post a Comment

Introduction

In this tutorial we will lean about what is java reflection API with examples. If we want to know information about a class at runtime we can use java reflection API. Knowing about class at runtime called as inspecting class at runtime. Java reflection API is useful to change the behaviour of a class at runtime, that means we can initiate an object, we can invoke method and we can change the value of field.

Where we can use java reflection API

In normal java applications there is no big use of java reflection API, but in realtime applications like performing JUnit test cases
  • Eclipse autocomplete feature to suggest methods
  • Creating beans in Spring Framework
  • Parsing ORM entity annotations  ( mapping data base fields with Java Entity class,  result set columns mapping with getter and setter methods of java object )
  • Debugging tools or code analysing tools
  • Mapping JSON properties with getter and setter methods of java object
Introspection is not equal to reflection, introspection means identifying type of objects at runtime. But reflection means modifying behaviour of a class at runtime with the help of introspection

What is the package of java reflection API

java.lang.reflect is the package need to import to implement reflection in our application. This package provides list of classes and interfaces for obtaining reflective information about classes and objects. Reflection allows programmatic access to information about the fields, methods and constructors of loaded classes, and the use of reflected fields, methods, and constructors to operate on their underlying counterparts, within security restrictions.

Following are list of classes available in java.lang.reflect package.

AccessibleObject: The AccessibleObject class is the base class for Field, Method and Constructor objects.
Array: The Array class provides static methods to dynamically create and access Java arrays.
Constructor: Constructor class provides information about, and access to, a single constructor for a class.
Executable: This is a shared superclass for the common functionality of Method and Constructor.
Field: A Field class provides information about, and dynamic access to, a single field of a class or an interface.
Method: A Method class provides information about, and access to, a single method on a class or interface.
Modifier: The Modifier class provides static methods and constants to decode class and member access modifiers.
Parameter: This class provides an i
nformation about method parameters.
Proxy: Proxy class provides static methods for creating dynamic proxy classes and instances, and it is also the superclass of all dynamic proxy classes created by those methods.
ReflectPermission: This is the Permission class for reflective operations.

Java reflection to inspect classes

In this section we will learn the procedure, how to use java reflection to inspect classes at runtime. Inspecting class is the entry point to apply java reflection operations at runtime. To get class information first you need to get Class object for a given object or for a given class name.

In the statement Student s= new Student() , s is an object and Student is a class name. There are three ways to get Class object ( java.lang.Class) , remember jvm will initiate an immutable instance of java.lang.Class for each and every class and interface executing at runtime of application.
An enum is a kind of class and an annotation is a kind of interface. Every array also belongs to a class that is reflected as a Class object that is shared by all arrays with the same element type and number of dimensions. The primitive Java types (boolean, byte, char, short, int, long, float, and double), and the keyword void are also represented as Class objects.
Class has no public constructor. Instead Class objects are constructed automatically by the Java Virtual Machine as classes are loaded and by calls to the defineClass method in the class loader.

Using object_name.getClass() method to get Class object

The following example uses a Class object to print the class name of an object:
void printClassName(Object obj) {
         System.out.println("The class of " + obj +
                            " is " + obj.getClass().getName());
     }
 

Using .class keyword to get Class object

It is also possible to get the Class object for a named type (or for void) using a class literal.For example:
System.out.println("The name of class Foo is: "+Foo.class.getName());

Using forName() method of Class

By usging Class.forName("class_name"), we can get Class object for a given class_name. While using forName() method we have to pass full qualified name of the class, for example if the class is in package com.code123.example and the class name Student.java is in this package then we have to pass full qualified name ( com.code123.example.Student ).
Class st = Class.forName("com.code123.example.Student")

Getting class name from Class object

There are two types of class names one is full qualified name and simple class name, com.code123.example.Student is a full qualified name, Student is a simple class name.
Class std=Class.forName("com.code123.example.factorymethodpattern.Client");
  System.out.println(std.getName());
Class std=Class.forName("com.code123.example.factorymethodpattern.Client");
  System.out.println(std.getSimpleName());

Metadata of a class

In this section we see how to get metadata of a class, metadata of class means class name, super class name, implemented interface and access modifiers/specifiers etc...

Get super class

By using getSuperclass() we can get super class object of Class type.
Class std = Class.forName("com.code123.example");
// getting super class Class object
Class spClass = std.getSuperclass();

Get implemented interfaces

If class implemented any interface we can get those interfaces by using getInterfaces() method of Class object.
Class[] interFaces=std.getInterfaces();
This will return an array of Class objects, because one class can implement more than one interfaces. To get deep level interfaces list you have to do recursively with getInterfaces() method.

Get public member classes

In some cases we can create inner classes in a class. If we want to get all inner classes ( public member classes ) in the current class and from its extended class and implemented interfaces we can use public Class[?] getClasses() which returns an array containing Class objects representing all the public classes and interfaces that are members of the class represented by this Class object. This includes public class and interface members inherited from super classes and public class and interface members declared by the class. This method returns an array of length 0 if this Class object has no public member classes or interfaces. This method also returns an array of length 0 if this Class object represents a primitive type, an array class, or void.
Class std = Class.forName("com.code123.example");
//get public member classes from Class object class and its superclasses and interface
Class[] pc= std.getClasses();
jaya
I love software designing, coding, writing and teaching...

Share this article

Related Posts

Post a Comment

Place your code in <em> </em> tags to send in comments | Do not add hyper links in commnet

Close

Subscribe our newsletter for the latest articles directly into your email inbox