Ticker

6/recent/ticker-posts

Reflection in Java — Java Reflection API Tutorial with Example

Reflection in Java — Java Reflection API Tutorial with Example

Introduction to Reflection:
Reflection in Java is a powerful feature that allows you to examine and modify the behavior of classes, interfaces, methods, and fields at runtime. It provides the ability to inspect the structure of a class, invoke methods, and access fields dynamically without knowing their names during compile time. The Java Reflection API is part of the java.lang.reflect package and is widely used in frameworks like Spring, Hibernate, and others.

1. Getting Class Information:

To obtain information about a class at runtime, you can use the following methods from the java.lang.Class class:

java
public class ReflectionExample {
public static void main(String[] args) {
try {
// Obtain Class object
Class<?> myClass = MyClass.class;

// Get the fully qualified class name
String className = myClass.getName();
System.out.println("Class Name: " + className);

// Get the simple class name (without package)
String simpleName = myClass.getSimpleName();
System.out.println("Simple Name: " + simpleName);

// Get the class modifiers (e.g., public, final, abstract, etc.)
int modifiers = myClass.getModifiers();
System.out.println("Modifiers: " + Modifier.toString(modifiers));

// Get the package name of the class
Package classPackage = myClass.getPackage();
System.out.println("Package: " + classPackage.getName());

// Get the superclass of the class
Class<?> superClass = myClass.getSuperclass();
System.out.println("Superclass: " + superClass.getName());

// Get the interfaces implemented by the class
Class<?>[] interfaces = myClass.getInterfaces();
System.out.println("Implemented Interfaces: ");
for (Class<?> intf : interfaces) {
System.out.println("- " + intf.getName());
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}

class MyClass implements Serializable, Cloneable {
// Class implementation here
}

2. Creating an Instance of a Class:

Reflection allows you to create an instance of a class dynamically using the newInstance() method:

java
public class ReflectionExample {
public static void main(String[] args) {
try {
Class<?> myClass = MyClass.class;
Object instance = myClass.newInstance();
System.out.println("Instance created: " + instance);
} catch (InstantiationException | IllegalAccessException e) {
e.printStackTrace();
}
}
}

class MyClass {
// Class implementation here
}

3. Invoking Methods Using Reflection:

You can invoke methods of a class dynamically through reflection:

java
import java.lang.reflect.Method;

public class ReflectionExample {
public static void main(String[] args) {
try {
Class<?> myClass = MyClass.class;
Object instance = myClass.newInstance();

// Get the method to be invoked
Method method = myClass.getMethod("methodName", parameterTypes);

// Invoke the method on the instance
Object result = method.invoke(instance, arg1, arg2, ...);
System.out.println("Result: " + result);
} catch (Exception e) {
e.printStackTrace();
}
}
}

class MyClass {
public String methodName(String arg) {
return "Hello, " + arg + "!";
}
}

4. Accessing and Modifying Fields Using Reflection:

Reflection allows you to access and modify fields of a class:

java
import java.lang.reflect.Field;

public class ReflectionExample {
public static void main(String[] args) {
try {
Class<?> myClass = MyClass.class;
Object instance = myClass.newInstance();

// Get the field to be accessed
Field field = myClass.getDeclaredField("fieldName");

// Make the field accessible (if it's private or protected)
field.setAccessible(true);

// Get the current value of the field
Object fieldValue = field.get(instance);
System.out.println("Current value: " + fieldValue);

// Set a new value for the field
field.set(instance, newValue);
System.out.println("New value: " + field.get(instance));
} catch (Exception e) {
e.printStackTrace();
}
}
}

class MyClass {
private String fieldName = "Initial Value";
}

Conclusion:

Reflection in Java is a powerful technique that provides great flexibility and enables you to work with classes dynamically at runtime. However, it should be used with caution due to its potential performance overhead and security risks. It's commonly used in frameworks and libraries to achieve various functionalities like dependency injection, object mapping, and more.

Post a Comment

0 Comments