Do you think IIT Guwahati certified course can help you in your career?
No
Introduction
Arrays in Java store multiple elements of the same type, but duplicates can cause inefficiencies or errors. This article explores various methods to remove duplicates from an array, including using sets, hash maps, frequency arrays, and space-optimized techniques.
What is reflection in Java?
Reflection in Java is a feature that allows a program to inspect and manipulate classes, methods, fields, and constructors at runtime. It is part of the java.lang.reflect package and is commonly used for debugging, testing, or building frameworks like dependency injection.
Uses of Reflection API
The Java reflection API is mainly used in
Developing IDE
Debugging
Testing tools
Loading drivers
Providing dynamic information
The Reflect Package
The Java reflect package(java.lang.reflect) encapsulates several important interfaces and classes, which define some methods used for reflection.
Some important classes of the java.lang.reflect package are shown below.
Field: This class is in java.lang.reflect provides information about the fields. It gathers some declarative information such as datatype, name, value and access modifiers of a variable.
Constructor: This class gives information about a class constructor. It is mainly used to gather the access modifiers, names and type of the parameters in a constructor.
Method: This class provides information about a method such as access modifiers, return type, name, parameter type and exception type.
Modifier: This class provides information about the class and the member access modifiers.
Java 'Class' Class
The Java Class class mainly performs two important tasks:
It provides some methods to get the metadata of a class at runtime.
It provides some methods to inspect and change the runtime behaviour of the class.
The important methods of the Java Class class are shown below.
public String getName(): This method returns the name of the class.
public Class getSuperClass(): This method returns the superclass reference.
public Class[] getInterfaces(): This method returns an array of interfaces implemented by the specified class.
public int getModifiers(): This method returns an integer value representing the specified class's modifiers. If you want to get the access specifiers of the given class, then you need to pass this integer value to the method “public static String toString(int i)”.
public static Class forName(String className) throws ClassNotFoundException: This method loads the class and returns the reference of the Class class.
public boolean isInterface(): It checks if it is an interface.
public boolean isArray(): It checks if it is an array.
public boolean isPrimitive(): It checks if it is primitive.
Java Reflection Class
We can get the complete information about a class in mainly three ways:
Using forName() method.
Using getClass() method.
Using .class syntax.
Using forName() Method
The below code will show you how to get the complete information about a class using the forName() method.
Code
public class Main{
public static void main(String[] args) throws ClassNotFoundException{
Class x = Class.forName("Main");
System.out.println(x.getName());
}
}
You can also try this code with Online Java Compiler
The below code will show you how to get the complete information about a class using the getClass() method.
Code
public class Main{
public static void main(String[] args) throws ClassNotFoundException{
Main obj = new Main();
Class x = obj.getClass();
System.out.println(x.getName());
}
}
You can also try this code with Online Java Compiler
We can determine the class object in mainly three ways:
Using isInterface() method.
Using isArray() method.
Using isPrimitive() method.
Code
class A{}
interface B{}
public class Main{
public static void main(String[] args) throws ClassNotFoundException{
Class c = Class.forName("A");
System.out.println(c.isInterface());
Class c2 = Class.forName("B");
System.out.println(c2.isInterface());
}
}
You can also try this code with Online Java Compiler
The below code will show you how can you get the metadata of a class.
Code
import java.lang.reflect.Modifier;
class A{}
interface B{}
interface D{}
abstract class C extends A implements B,D{}
public class Main{
public static void main(String[] args) throws ClassNotFoundException{
Class a = C.class;
System.out.println("Name of the class is: " + a.getName());
System.out.println("Name of the superclass is: " + a.getSuperclass().getName());
Class[] lis = a.getInterfaces();
System.out.print("Implemented interfaces are: ");
for(Class i : lis) {
System.out.print(i.getName() + " ");
}
System.out.println();
int mod = a.getModifiers();
System.out.println("Access modifiers of the class are: " +Modifier.toString(mod));
}
}
You can also try this code with Online Java Compiler
The below code will show you how can you get the metadata of a variable.
Code
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
// Class C contains some variables
class C {
public static int var1 = 8608;
public static int var2 = 9371;
public static String str = "Hello";
}
public class Main {
public static void main(String[] args) throws IllegalAccessException,IllegalArgumentException{
// Creating the object of the class C
C ob = new C();
Class var = ob.getClass();
// get the metadata of all the fields of class C
Field[] field= var.getDeclaredFields();
// run a loop to print name of the variable,datatypes, access modifiers
for(Field f : field) {
System.out.println("Variable name : "+f.getName());
System.out.println("Datatype:"+f.getType());
int mod = f.getModifiers();
System.out.println("Access Modifiers: "+Modifier.toString(mod));
System.out.println("Value: " + f.get(f));
System.out.println();
}
}
}
You can also try this code with Online Java Compiler
The below code will show you how to get the metadata of a method
Code
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
// Class C contains some methods
class C {
public void methhod1() throws IllegalAccessException{
System.out.println("Demo method1");;
}
public void method2(int a , int b) throws IllegalArgumentException{
System.out.println("Demo method2");
}
public void method2(int a , int b , String c){
System.out.println("Demo method3");
}
}
public class Main {
public static void main(String[] args) throws IllegalAccessException,IllegalArgumentException{
// Creating the object of the class C
C ob = new C();
Class var = ob.getClass();
// get the metadata of all the Methods of class C
Method[] method= var.getDeclaredMethods();
// run a loop to print name of the method,return types, access modifiers, parameters type and exceptions thrown by the method
for(Method m : method) {
System.out.println("Method name : "+m.getName());
System.out.println("Return type:"+m.getReturnType());
int mod = m.getModifiers();
System.out.println("Access Modifiers: "+Modifier.toString(mod));
System.out.println("Method parameters types: ");
Class[] params = m.getParameterTypes();
for(Class i: params) {
System.out.println(i.getName() + " ");
}
Class[] exceptions = m.getExceptionTypes();
System.out.println("Exception thrown by the method : ");
for(Class i : exceptions) {
System.out.println(i.getName() + " ");
}
System.out.println();
}
}
}
You can also try this code with Online Java Compiler
The below code will show you how we can get the metadata of a constructor
Code
import java.lang.reflect.Constructor;
import java.lang.reflect.Modifier;
import java.rmi.RemoteException;
// Class C contains some Constructors
class C {
public C() throws IllegalAccessException{}
public C(int a) throws IllegalArgumentException{}
public C(int a , int b , String c) throws RemoteException{}
}
public class Main {
public static void main(String[] args) throws IllegalAccessException,IllegalArgumentException{
// Creating the object of the class C
C ob = new C();
Class var = ob.getClass();
// get the metadata of all the Constructors of class C
Constructor[] constructor= var.getDeclaredConstructors();
// run a loop to print name of the Constructor, constructor modifiers, parameters type and exceptions thrown by the Constructor
for(Constructor c : constructor) {
System.out.println("Constructor name : "+c.getName());
int mod = c.getModifiers();
System.out.println("Constructor Modifiers: "+Modifier.toString(mod));
System.out.println("Constructor parameters types: ");
// params stores the parameter types of the constructor
Class[] params = c.getParameterTypes();
for(Class i: params) {
System.out.println(i.getName() + " ");
}
// exception stores the exceptions thrown by the constructor
Class[] exceptions = c.getExceptionTypes();
System.out.println("Exception thrown by the Constructor : ");
for(Class i : exceptions) {
System.out.println(i.getName() + " ");
}
System.out.println();
}
}
}
You can also try this code with Online Java Compiler
The advantages and disadvantages of the Reflection API in java are discussed below:
Advantages
Disadvantages
We can inspect the interfaces, classes, methods, and fields during runtime without using their name in the compile time.
Using reflection violates the OOPs concept, like accessing private members using reflection, which breaks the encapsulation concept.
Debuggers use the reflection properties to examine the private members of a class.
There are security issues in the reflection API.
The performance of the reflection operations is very slow.
Frequently Asked Questions
What is the importance of the Java reflection API?
The importance of the Java reflection API is that it allows you to examine or modify the runtime behaviour of a class at runtime.
What are the limitations of Java reflection?
The limitations of Java reflection include the low performance of its operation, security risk etc.
Can Java reflection API access the private fields of a class?
Yes, it can access the private fields of a class using the setAccessible(true) on the method or field object which you want to access.
What is the alternative to Java reflection?
One alternative to Java reflection is to generate a class file dynamically.
Conclusion
In this article, we explored the Java Reflection API, starting with its basics and moving through its core features and practical use cases. Reflection offers powerful runtime capabilities, making it essential for dynamic and flexible Java applications.