Reflection API in Java

The term reflection or reflector has a different meaning depending on the context they revolve around. Here in Java, reflection is an API that examines or modifies the behaviors of methods, classes and interfaces at runtime.

Reflection API in Java:

Reflection is a process of examining or modifying the run time behavior of a class at run time. It is an API (Application Programming Interface). The java.lang.Class is where we can find various methods to receive the metadata of the class. Using this metadata, we can check and change the run time behaviour of the class.

When it comes to reflection, the packages java.lang and java.lang.reflect provides the classes for it.

More about Reflection in Java:

  • All the classes that perform reflection are present in the package java.lang.reflect.
  • This reflection gives details about the classes and the objects and methods that are related to them.
  • We can easily call a method at run time without considering its access specifier via reflection.

java reflection api

Areas where we can implement Java reflection:

The areas where the reflection API of java is mainly used are:

  • Integrated Development Environment(IDEs) like MyEclipse, Eclipse, NetBeans, etc.
  • Test Tools
  • Debugger

The purpose of java.lang.Class class:

This class helps us in performing a couple of necessary tasks:

It gives access to get the metadata of a class at run time.

It gives access to the methods that check and modify the runtime behaviour of the class.

Getting Information using Java Reflection API

Using reflection, we can get much information like:

1. Class: The getClass() method provides the class name of the object.

2. Constructors: The getConstructors() method returns the public constructors of the class where the object is present.

3. Methods: The getMethods() method provides the public methods of the class where the object is present.

Sample code to implement getting the information using reflection API:

import java.lang.reflect.Method;
import java.lang.reflect.Field;
import java.lang.reflect.Constructor;
class FirstCode{
private String str;
public FirstCode() {
str = "Learn Java with FirstCode";
}
public void method1() {
System.out.println("\nThe string is: " + str);
}
public void method2(int num1) {
System.out.println("\nThe number is: " + num1);
}
private void method3() {
System.out.println("\nThe private method is invoked");
}
}
public class FirstCodeCourse{
public static void main(String args[]) {
FirstCode obj = new FirstCode();
Class c = obj.getClass();
System.out.println("\nThe name of the class is: " + c.getName());
Constructor constructor = c.getConstructor();
System.out.println("\nThe name of the constructor is: " + constructor.getName());
System.out.println("\nThe public methods in the class are: ");
Method[] methods = c.getMethods();
for (Method method: methods)
System.out.println(method.getName());
Method methodCall1 = c.getDeclaredMethod("Method2", int.class);
methodCall1.invoke(obj, 23);
Field field = c.getDeclaredField("str");
field.setAccessible(true);
field.set(obj, "Java");
Method methodCall2 = c.getDeclaredMethod("Method1");
methodCall2.invoke(obj);
Method methodCall3 = c.getDeclaredMethod("Method3");
methodCall3.setAccessible(true);
methodCall3.invoke(obj);
}
}

Output:

The name of the class is: FirstCode
The name of the constructor is: FirstCode
The public methods of the class are:
Method2
Method1
wait
wait
wait
equals
toString
hashCode
getClass
notify
notifyAll
The number is: 23
The string is: Java
The private method is invoked

Popular methods of Java Class class:

Sl.No Method Description
1 public String getName() It returns the name of the class.
2 public static Class forName(String className) throws ClassNotFoundException It loads the class and returns the reference of the class Class
3 public Object newInstance() throws InstantiationException, IllegalAccessException It creates a new instance
4 public boolean isInterface() It checks if it is an interface
5 public boolean isPrimitive() It checks if it is primitive
6 public Class getSuperclass() It returns the superclass class reference
7 public Field() getDeclaredFields() throws SecurityException It returns the total number of fields of the class
8 public boolean isArray() It checks if it an array
9 public Method() getDeclaredMethods() throws SecurityException It returns the total number of methods present in this class
10 public Constructor() getDeclaredConstructors() throws SecurityException It returns the total number of constructors present in this class
11 public Method getDeclaredMethod(String name, Class[] parameterTypes) throws NosuchMethodException, SecurityException It returns the method class instance

Ways to get the object of Java Class class:

To get the object of Class class, we can follow three different ways:

  • By using forName() method of Class class
  • Using the getClass() method of Object class
  • Using the .class syntax

Let us now look at how these ways can be implemented in a brief manner.

1. forname() method of Class class in java:

The forName() method either loads the class dynamically or during the run time. It returns the object of the Class class. It cannot be applied to primitive types and can only be used if the exact name of the class is known.

Sample program to implement the forName method to attain the instance of the class:

class FirstCode{}
public class Course (){
public static void main(String args[]) throws Exception{
Class c = Class.forName(“Learn Java with FirstCode”);
Ssytem.out.println(c.getName()); 
}
}

Output:

Learn Java with FirstCode

2. getClass() method of Object Class:

This method is a part of the Object class and it returns the instance of Class class. When we are clear about the type, this method can be useful. It also goes well with primitives.

class FirstCode{}
class Courses{
void printName(Object obj){
Class c = obj.getClass();
System.out.println(c.getName());
}
public static void main(String args[]){
FirstCode fc = FirstCode();
Course cour = new Course(fc);
}
}

3. The .class syntax:

Sometimes, we might face the situation when we know the type of the class but the instance is absent. At such instances, we can still obtain a Class by appending “.class” to the type’s name.

class Firstcode{
public static void main(String args[]){
Class c = boolean.class;
System.out.println(c.getName());
Class c2 = FirstCode.class;
System.out.println(c2.getName());
}
}

Output:

booleanFirstCode

Determining the class object in java:

Here are the methods that let you determine the class object:

1. public boolean isInterface(): It determines if the specified Class object represents an interface type.

2. public boolean isArray(): It determines if the Class object represents an array.

3. public boolean isPrimitive(): It determines if the Class object represents a primitive type.

How to get data by Java reflection:

Using reflection, we can attain various data about:

  • Class: The get class() method gets the class name where an object has a place.
  • Constructors: The getConstructors() technique is used to attain the public constructors of the class where an object has a place.
  • Strategies: The getMethods() technique is used to attain the public methods of the class where an object has a place.

Sample program to determine the class object:

class FirstCode{}
interface Course{}
class CourseList{
public static void main(String args[]){
try{
Class c = Class.forName(“FirstCode”);
System.out.println(c.isInterface());
Class c2 = Class.forName(“Interface”);
System.out.println(c2.isInterface()); 
}
catch(Exception e) {System.out.println(e);}
}
}

Output:

falsetrue

Example of Reflection API to determine the type of object:

class FirstCode{}
interface Course{}
class FirstCodeCourse{
public static void main(String args[]){
try{
Class c = class.forName(“Learn Java with FirstCode”);
System.out.println(c.isInterface());
 Class c2 = class.forName(“Learn C++ with FirstCode”);
System.out.println(c2.isInterface());
}
catch(Exception e){
System.out.println(e);
}
}
}

Output:

falsetrue

Getting Superclass and Access Modifier in Java:

To get the details of any superclass, we can use the getSuperclass() method. The Class class gives access to the method getModifier that returns the access modifier of the class in Integer.

Sample program to implement getting superclass and access modifier in Java:

import java.lang.Class;
import java.lang.reflect. * ;
interface FirstCode{
public void display();
}
public class Course implements FirstCode{
public void display() {
System.out.println("Learn Java with FirstCode");
}
}
class FirstCodeReflection{
public static void main(String[] args) {
try {
Course c1 = new Course();
Class obj = c1.getClass();
int modifier = obj.getModifiers();
System.out.println("Access Modifier: " + Modifier.toString(modifier));
Class superClass = obj.getSuperclass();
System.out.println("Superclass: " + superClass.getName());
}
catch(Exception e) {
e.printStackTrace();
}
}
}

Output:

Access Modifier: public
Superclass: java.lang.Object

Getting Interfaces in Java:

To attain the information about the interfaces implemented by the class, we can use the getInterfaces() method. It returns an array of interfaces.

Sample program to implement getting interfaces in Java:

import java.lang.Class;
import java.lang.reflect. * ;
interface Bike {
public void show();
}
interface Bicycle {
public void speed();
}
class TwoWheeler implements Bike,
Bicycle {
public void show() {
System.out.println("This is a bike");
}
public void speed() {
System.out.println("This bike operates at high speed");
}
}
class FirstCodeReflection{
public static void main(String[] args) {
try {
TwoWheeler t = new TwoWheeler();
Class obj = t.getClass();
Class[] objInterface = obj.getInterfaces();
for (Class c: objInterface) {
System.out.println("Interface Name: " + c.getName());
}
}
catch(Exception e) {
e.printStackTrace();
}
}
}

Output:

Interface Name: Bike
Interface Name: Bicycle

Advantages of java reflection

1. Extensible features: We can easily create an application that uses the external and user-defined classes. As we can create instances of extensible objects with the help of their fully-qualified names, this becomes easily possible.

2. Debugging and test tools: Reflection helps the debuggers to check private members on classes.

3. Developers can code easily: It lets the programmers easily create Visual Development Environments and class browsers.

Disadvantages of java reflection:

1. Performance overhead: The reflective operations show slower performance than the non-reflective ones. Therefore, it is better to avoid the in blocks that are frequently called.

2. Exposure of Internals: The reflective code breaks abstractions. This leads to a change of behavior when the platform gets upgraded.

3. No more privacy: Reflection breaks the rules of encapsulation and allows access to private methods and fields.

Important observations about reflection in Java:

1. Once we know a method’s name, we can easily invoke it via reflection and parameter types. There are two specific methods for this purpose:

a. getDeclaredMethod(): It creates an object to invoke the method.

Syntax for this method:

Class.getDeclaredMethod(name, parametertype)

Here, name: Method’s name that require an object

parametertype: Array of Class objects

b. invoke() method:

It invokes the method of a class at runtime.

Syntax for this method:

Method.invoke(Object, parameter)

If this method of class restricts to accept any parameter, we can pass null as an argument.

2. We can also access the private methods and variables of a class with Reflection.

We can access these values using the class object and invoke the method by using the same object. There are two methods to achieve this:

a. Class.getDeclaredField(FieldName): It returns the private field of the class. It returns an object of the Field type for the given field name.

b. Field.setAccessible(true): It allows to access the field irrespective of the access modifier that is used with the field.

Summary

This was all about reflection API in java. Using reflectors, we can examine the process of the run time behaviour of a class at run time.

Leave a Reply

Your email address will not be published. Required fields are marked *