Java Reflection

What is Java Reflection?

It is the process of identifying or modifying the behavior of a class at run time. The reflection API allows a developer to inspect interfaces, classes, fields and methods at run time without knowing the names at compile time.

Using Java Reflection, while inspecting classes, one can obtain information about ClassName, Class Modifiers, Package Information, Super class, Implemented Interfaces, Constructors, Methods, fields etc

How to use Java Reflection?

a) How to obtain the class object at run time assuming class name is known at compile time?

Class object = obj.class;

b) How to obtain the complete class name from the class object?

String className = object.getName();

c) How to obtain the simple class name without package name from the class object?

String className = object.getSimpleName();

d) How to obtain the information about the super class from the class object?

Class scn = object.getSuperClass();

e) How to obtain information about the interfaces implemented by a given class?

Class[] loi = object.getInterfaces();

f) How to get the fields of the class?

Field[] fields = object.getFields();

g) How to get the methods of the class?

Method[] method = object.getMethods();

h) How to get the constructors of the class?

Constructor[] constructors = object.getConstructors();

i) How to invoke the private method of a class?

// Imagine a class Employee which has a private method called display.

public class Employee {

private void display() {

System.out.println(“Inside the method display”);

}

}

// This private method is called from another class called Company using Reflection.

public class Company {

public static void main (String[] args) throws Exception {

Class class = Class.forName(“Employee”);

Object obj = class.newInstance();

/* Invoke the method named “display” with parameters. Here null indicates that parameters are not present in the method signature.*/

Method m = obj.getDeclaredMethod(“display”, null);

m.setAccessible(true); // sets the private method as accessible

m.invoke(obj, null); // invokes the method.

}

}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s