Object reflection in Java

Explain what object reflection is in Java and why it is useful.

Object Reflection is a feature in Java which provides a way to get reflective information about Java classes and objects, such as:

  1. Getting information about methods and fields present inside the class at run time.
  2. Creating a new instance of a class.
  3. Getting and setting the object fields directly by getting field reference, regardless of what the access modifier is.
	public static void main(String[] args) {
		try {
			Class c = Class.forName("java.sql.Connection");
			Method m[] = c.getDeclaredMethods();
			for (int i = 0; i < 3; i++) {
		} catch (Throwable e) {

This code’s output is the names of the first 3 methods inside the “java.sql.Connection” class (with fully qualified parameters):
public abstract void java.sql.Connection.setReadOnly(boolean) throws java.sql.SQLException
public abstract void java.sql.Connection.close() throws java.sql.SQLException
public abstract boolean java.sql.Connection.isReadOnly() throws java.sql.SQLException
Why it is useful:

  1. Helps in observing or manipulating the runtime behavior of applications.
  2. Useful while debugging and testing applications, as it allows direct access to methods, constructors, fields, etc.
    1. 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 )

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s

%d bloggers like this: