Reflection API — Java. Do you want to access or invoke private members? Lets do it.
Hey guys, hope you are doing great! Today I would like to discuss about Reflection API available in Java. Reflection is an ability of a program to analyse code at run time. It can be used to analyse or modify the behaviour of member variables and methods during runtime. This api is available to all the classes since it belongs to “java.lang.reflect”. The most important classes of “java.lang.reflect” are,
- Method
- Field
- Constructor
If you want to know to which class an object belongs to, reflection will help you get that information, and if you want to list what methods are available in a class then reflection is the right choice. Irrespective of access specifier provided to the methods, we can access them with the help of reflection.
Lets dive into coding part. Below is a dummy class which contains a private variable, a public constructor which assigns value to private variable, public methods with and without parameters, and one private method.
Now, from another class we are going to access all the above class members.
First, we need to create an object to the above class.
Dummy obj = new Dummy();
Now, we need to get class object.
Class cls = obj.getClass();
Now, to get the hold of constructor, use this
Constructor cons = cls.getConstructor();
Thats it, we can get the name of the constructor by below code
cons.getName();
To list methods which are present in “Dummy” class, use below code
Method[] meths = cls.getMethods();for(Method met : meths) System.out.println("Methods: " + met.getName());
To get the hold of the individual method and invoke the method at run time, we have to use “getDeclaredMethod()” and have to pass the name of the method as an argument to the above method. And then we need to use “invoke()” method to access at runtime. Please follow below code.
Method meth1 = cls.getDeclaredMethod("reflectOne");meth1.invoke(obj);
To access private method, we have to set the accessible to true for that method. We can pass arguments as well if that method contains any parameters. One thing, the type of parameter must be mentioned. Please follow the code carefully.
Method meth2 = cls.getDeclaredMethod("reflectTwo", int.class);meth2.setAccessible(true);meth2.invoke(obj, 123);
To access private variable, below is the code.
Field fld = cls.getDeclaredField("str");fld.setAccessible(true);fld.set(obj, "hello reflection...");
So, the final code is as follows,
Please let me know if you have any doubts or further clarifications, and also please correct me if I have done anything wrong with the above explanation…I’m happy to help you. Happy coding guys….Do not fall in love, girl will stab you from your behind….