Reflection in programming

Posted: Saturday, February 19, 2011 by Venkat Pola in Labels:
0

Generally we might need to modify the structure and behaviour of a program at runtime
(or )
we have to call a method of a class but we will get class name and method at runtime only. I mean during compile time we dont know what to use.

In these type of scnerios we can opt for reflection style of programming. I will show you sample program how to use in different languages.

Java:-
// No Reflection
new Foo().hello();
// After Reflection
Class cls = Class.forName("Foo");
cls.getMethod("hello", null).invoke(cls.newInstance(), null);

Javascript:-
// No Reflection
new Foo().hello()
// After Reflection
new (eval('Foo'))()['hello']()

Python:-
# No Reflection
Foo().hello()
# After Reflection
getattr(globals()['Foo'](), 'hello')()

Enhanced by Zemanta

0 comments: