Sunday, September 27, 2009

Reflection


Reflection is a functional extension to the object-oriented programming paradigm. It includes self-examination, self-modification, and self-replication. It is commonly used by programs which require the ability to examine or modify the runtime behavior of applications. This is typically accomplished by dynamically assigning program code at runtime.

E.g. In C#, here's how you would achieve reflection:
//Without reflection
Foo foo = new Foo();
foo.Hello();

//With reflection
Type t = Assembly.GetCallingAssembly().GetType("FooNamespace.Foo");
t.InvokeMember("Hello", BindingFlags.InvokeMethod, null, Activator.CreateInstance(t), null);

Reflection is powerful, but should not be used indiscriminately. The following concerns should be kept in mind when accessing code via reflection:
  •  Performance Overhead
Because reflection involves types that are dynamically resolved, certain optimizations cannot be performed. Consequently, reflective operations have slower performance than their non-reflective counterparts, and should be avoided in sections of code which are called frequently in performance-sensitive applications.
  •  Security Restrictions
Reflection requires a runtime permission which may not be present when running under a security manager. This is in an important consideration for code which has to run in a restricted security context.
  •  Exposure of Internals
Since reflection allows code to perform operations that would be illegal in non-reflective code, such as accessing private fields and methods; the use of reflection can result in unexpected side-effects. This may render code dysfunctional and may destroy portability. Reflective code breaks abstractions and therefore may change behavior with upgrades of the platform.

P.S. Since this is an advanced feature of .Net framework, if you can use this in your application, you can call yourself an "advanced programmer"! :)

No comments: