What is Reflection
"Reflection" is a language's ability to inspect and dynamically call classes, methods, attributes, etc. at runtime.
For example, Suppose you have an object of an unknown type in Java, and you would like to call a "Callme" method on it if one exists. Java's static typing system isn't really designed to support this unless the object conforms to a known interface, but using reflection, your code can look at the object and find out if it has a method called "Callme" and then call it if you want to.Suppose we want to call
Advantage :-
1. Reflection is used by developer to increase code coverage of classes by accessing private member and method of that classes.
Drawbacks :-
1. Reflection expose private method and field.
This class method call at run time
"Reflection" is a language's ability to inspect and dynamically call classes, methods, attributes, etc. at runtime.
For example, Suppose you have an object of an unknown type in Java, and you would like to call a "Callme" method on it if one exists. Java's static typing system isn't really designed to support this unless the object conforms to a known interface, but using reflection, your code can look at the object and find out if it has a method called "Callme" and then call it if you want to.Suppose we want to call
Advantage :-
1. Reflection is used by developer to increase code coverage of classes by accessing private member and method of that classes.
Drawbacks :-
1. Reflection expose private method and field.
This class method call at run time
package com.kodemaker; public class TestReflection { public void testReflectionMethod(){ System.out.println("Identify my class runtime and call me Hello Reflection you have successfully tested." ); } }
This class load "TestReflection" class at run time, create it object, print it name and call it method "testReflectionMethod"
package com.kodemaker; import java.lang.reflect.Method; public class ReflectionMain { public static void main(String[] args) { Class withousParameter[] = {}; try{ Class testReflection = Class.forName("com.kodemaker.TestReflection"); System.out.println(testReflection.getName()); Object testReflectionObj = testReflection.newInstance(); Method method = testReflection.getDeclaredMethod("testReflectionMethod", withousParameter); method.invoke(testReflectionObj, null); }catch(Exception ex){ ex.printStackTrace(); } } }
Output:-
com.kodemaker.TestReflection Identify my class runtime and call me Hello Reflection you have successfully tested.
No comments:
Post a Comment