Reflection in Java with example
In this tutorial, you are going to learn about the concept of Reflection API (Application Program Interface) in Java. This is a concept that is not used commonly but is very helpful in various frameworks of Java. It is used for examination and modification of classes, variables, interfaces and so on at runtime.
Example Code for Demonstration of Reflection
Step1: Create Package and Import-classes
package javaapplication4; import java.io.*; import java.lang.reflect.*;
Step2: Create a class to be Examined
class Shape { int s1,s2,res; Shape() { s1=0; s2=0; res=0; } public void square(int side) { s1=side; s2=side; res=side*side; } public void rectangle(int side1, int side2) { s1=side1; s2=side2; res=side1*side2; } }
Step3: Create another class for the main function for using Reflection Concept – In this demonstration, we are using the reflection concept to find the name of the class and the functions that are public.
class JavaApplication4 { public static void main(String[] args)throws Exception { Shape s = new Shape(); Class c = s.getClass(); System.out.println("Classes are - "+c.getName()); System.out.println("The public functions in the Class Shape are : "); Method[] c2 = c.getMethods(); for (Method count:c2) System.out.println(count.getName()); }
Note: Private functions will not be displayed.
Output:-
Classes are - javaapplication4.Shape The public functions in the Class Shape are : square rectangle wait wait wait equals toString hashCode getClass notify notifyAll
Conclusion
In the above demonstration, you get an idea of how to find the name of a class and public functions. Similarly, this can be done to know the names of interfaces, variables, and constructors. There are various other uses of reflection API in Java such as you can modify the function at run-time. But it also has a drawback that it decreases the performance of code as it increases the run-time.
Leave a Reply