Monday, February 16, 2015

Java Reflection and its usage. #interview

The name reflection is used to describe code which is able to inspect other code in the same system (or itself).
Reflection is a key mechanism to allow an application or framework to work with code that might not have even been written yet! Reflection allows instantiation of new objects, invocation of methods, and get/set operations on class variables dynamically at run time without having prior knowledge of its implementation.

For example: say you have an object of an unknown type in Java, and you would like to call a 'doSomething' 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 'doSomething' and then call it if you want to.

imagine the object in question is foo
Method method = foo.getClass().getMethod("doSomething", null);
method.invoke(foo, null);
One very common use case in Java is the usage with annotations. JUnit 4, for example, will use reflection to look through your classes for methods tagged with the @Test annotation, and will then call them when running the unit test.


Reflection is important since it lets you write programs that does not have to "know" everything at compile time, making them more dynamic, since they can be tied together at runtime. The code can be written against known interfaces, but the actual classes to be used can be instantiated using reflection from configuration files.

Usage :Java reflection is useful while writing frameworks and all, spring seems to use it.
Reflection is usually slower then statically compiled methods, you loose compile time type safety.
Everywhere you want to be able to dynamically plug in classes into your code. Lot's of object relational mappers use reflection to be able to instantiate objects from databases without knowing in advance what objects they're going to use. Plug-in architectures is another place where reflection is usefull. Being able to dynamically load code and determine if there are types there that implement the right interface to use as a plugin is important in those situations

No comments:

Post a Comment

Creating mirror of BST