Note: Through reflection, we can access the private variables and methods of a class with the help of its class object and invoke the method by using the object as discussed above. Syntax: Method(Object, parameter) Tip: If the method of the class doesn’t accept any parameter then null is passed as an argument. Syntax: The syntax for this method Class(name, parametertype) Parameters: Name of a method whose object is to be created An array of Class objects Method 2: invoke(): It invokes a method of the class at runtime we use the following method. invoke() Method 1: getDeclaredMethod(): It creates an object of the method to be invoked. We use two methods for this purpose as described below before moving ahead as follows: 1. We can invoke a method through reflection if we know its name and parameter types. ![]() Methods The getMethods() method is used to get the public methods of the class to which an object belongs. Constructors The getConstructors() method is used to get the public constructors of the class to which an object belongs. Reflection can be used to get information about class, constructors, and methods as depicted below in tabular format as shown: Class The getClass() method is used to get the name of the class to which an object belongs. Through reflection, we can invoke methods at runtime irrespective of the access specifier used with them. So we are illustrating the package with visual aids to have a better understanding as follows: Reflection gives us information about the class to which an object belongs and also the methods of that class that can be executed by using the object. The required classes for reflection are provided under java.lang package which is essential in order to understand reflection. Reflection in Java Reflection is an API that is used to examine or modify the behavior of methods, classes, and interfaces at runtime.
0 Comments
Leave a Reply. |