Reflection in Java | Java Reflection API Tutorial

Get Job-ready: Java Course with 45+ Real-time Projects! - Learn Java

In our previous Java tutorial, we looked at Iterators in Java. Today, in this article, we are going to discuss Reflection in Java. Here, we will see what Java Reflection is & how it can be utilized to get data.

Moreover, we will look at the pros and cons of Java reflection. Along with this, we will understand the sample code using Java reflection and its class.

So, let’s start Reflection in Java.

Reflection in Java | Java Reflection API Tutorial

Reflection in Java | Java Reflection API Tutorial

What is Reflection in Java?

Reflection in Java is an Application Programming Interface(API) that is utilized at runtime to change classes, methods, and interfaces.

It is an API that is utilized to look at or change the behavior of methods, classes, and interfaces at runtime.

  • The required classes for reflection in Java are given under java.lang.reflect package.
  • Reflection gives us data about the class to which an object belongs, and furthermore, the methods for that class are executed by utilizing the object.
  • Through reflection, we can summon a method at runtime independent of the access specifier utilized with it.

Do you know the Working of Java Packages?

Reflection in Java

Java Reflection- Reflection API

How to Get Data Using Java Reflection?

Reflection can be utilized to get data about :

  • Class- The getClass() method is utilized to get the name of the class to which an object belongs.
  • Constructors- The getConstructors() technique is utilized to get the public constructors of the class to which an object belongs.
  • Strategies- The getMethods() technique is utilized to get the public methods for the class to which an object belongs.

Let’s revise Java Copy Constructor | Constructor Overloading in Java

import java.lang.reflect.Method;
import java.lang.reflect.Field;
import java.lang.reflect.Constructor;
class Test
{    private String s;
   public Test()  { s = "DataFlair"; }
   public void method1()  {
       System.out.println("The string is " + s);
   }
   public void method2(int n)  {
       System.out.println("The number is " + n);
   }
   private void method3() {
       System.out.println("Private method invoked");
   }
}
class Demo
{
   public static void main(String args[]) throws Exception
   {
       Test obj = new Test();
       Class cls = obj.getClass();
       System.out.println("The name of class is " +
                           cls.getName());
       Constructor constructor = cls.getConstructor();
       System.out.println("The name of constructor is " +
                           constructor.getName());
       System.out.println("The public methods of class are : ");
       Method[] methods = cls.getMethods();
       for (Method method:methods)
           System.out.println(method.getName());
       Method methodcall1 = cls.getDeclaredMethod("method2",
                                                int.class);
       methodcall1.invoke(obj, 19);
       Field field = cls.getDeclaredField("s");
       field.setAccessible(true);
       field.set(obj, "JAVA");
       Method methodcall2 = cls.getDeclaredMethod("method1");
       methodcall2.invoke(obj);
       Method methodcall3 = cls.getDeclaredMethod("method3");
       methodcall3.setAccessible(true);
       methodcall3.invoke(obj);
   }
}

Output 

The name of the class is Test

The name of constructor is

Test The public methods of class are:

method2

method1

wait

wait

equals

wait

toString

hashCode

getClass

notify

notifyAll

The number is 19

The string is JAVA

Private method invoked

Learn Singleton Class in Java – Two Simple Ways For Implementing

 Important points:

  • We can summon a strategy through reflection on the off chance that we know its name and parameter compositions. Hence, we use two strategies for this reason
  • getDeclaredMethod(): To make a question of a method to conjure.

A Syntax for Java Reflection: get declared method–

Class.getDeclaredMethod(name, parametertype)
name- the name of method whose object is to be created
parametertype - parameter is an array of Class objects

invoke(): At runtime, to invoke a method of a class, we use the following method-

A Syntax for the invoke method-

Method.invoke(Object, parameter)

Java Wildcard – Types of Wildcard in Java

So, if the Java reflection class method doesn’t accept any parameter, then an argument is passed as null.

  • Through reflection, we can get to the private methods and variables for a class with the assistance of its class question and therefore, summon the method by utilizing the object as talked about above. Hence, we use two strategies for this reason.
  • Class.getDeclaredField(FieldName): Used to get the private field.
  • Field.setAccessible(true): It allows getting to the field independent of the entrance modifier utilized with the field.

Advantages of Java Reflection –

  • Extensibility Features: An application may make use of outer, user-defined classes by making examples of extensibility objects utilizing their completely qualified names.
  • Debugging and testing devices: Debuggers utilize the property of reflection to look at private members of classes.
  • Effective to use: The execution at runtime enables the efficient use of the tools to debug the methods and classes.

Disadvantages of Java Reflection –

  • Execution Overhead: Reflective tasks have slower execution. This is because the class and method checks are performed at run-time. Thus, this results in degrading the performance of the application.
  • Introduction of Internals: Reflective code breaks deliberations.
  • Breach of Safety: The reflection in Java allows access to private members of a class. Therefore, the private members are reachable, which indicates a high safety risk.

Learn about Collection Framework in Java – Hierarchy, Need & Advantages

Security Considerations:

Java Reflection is a powerful tool that can be used to bypass access modifiers and invoke private methods or access private fields. Therefore, this can be beneficial in certain situations, such as unit testing frameworks that need to access private members for testing purposes. However, it’s important to be aware of the security implications. Therefore, Malicious code could potentially exploit reflection to access or modify sensitive data that would normally be hidden.

However, to mitigate these risks, it’s generally recommended to avoid using reflection in production code unless necessary. Therefore, when using reflection, it’s advisable to implement proper security checks to ensure that only authorized code can access restricted members

Conclusion

Hence, we have a complete understanding of reflection in Java. Along with this, we saw the advantages and disadvantages of Java Reflection. At last, we learned the Java reflection class and java reflection invokes a method with the help of an example. Furthermore, if you have any queries, feel free to ask through the comment section.

For reference

Did you like this article? If Yes, please give DataFlair 5 Stars on Google

courses

DataFlair Team

DataFlair Team creates expert-level guides on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Our goal is to empower learners with easy-to-understand content. Explore our resources for career growth and practical learning.

Leave a Reply

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