Important Observations of Reflection API
- We can invoke an method through reflection if we know its name and parameter types. We use below two methods for this purpose
getDeclaredMethod() : To create an object of method to be invoked. The syntax for this method isClass.getDeclaredMethod(name, parametertype) name- the name of method whose object is to be created parametertype - parameter is an array of Class objects
invoke() : To invoke a method of the class at runtime we use following method–
Method.invoke(Object, parameter) If the method of the class doesn’t accepts any parameter then null is passed as argument.
- 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. We use below two methods for this purpose.
Class.getDeclaredField(FieldName) : Used to get the private field. Returns an object of type Field for specified field name.
Field.setAccessible(true) : Allows to access the field irrespective of the access modifier used with the field.
Comments
Post a Comment