A reflection-oriented program component can monitor the execution of an enclosure of code and can modify itself according to a desired goal related to that enclosure.
Reflection is one of those things like multi-threading where everyone with experience of it says “Don’t use it unless you absolutely have to”.
2. Agenda
What is Reflection?
How to get the object Class class
Reflection vs Metaprogramming
Why do we need reflection?
Demo
Real Usage Examples
3. What is Reflection?
Reflection is used for observing and modifying program execution at runtime.
A reflection-oriented program component can monitor the execution of an
enclosure of code and can modify itself according to a desired goal related to that
enclosure.
Reflection is one of those things like multi-threading where everyone with experience of
it says “Don’t use it unless you absolutely have to”.
4. Example:
// without reflection
Foo foo = new Foo();
foo.hello();
// with reflection
Object foo = Class.forName("complete.classpath.and.Foo").newInstance();
// Alternatively: Object foo = Foo.class.newInstance();
Method m = foo.getClass().getDeclaredMethod("hello", new Class<?>[0]);
m.invoke(foo);
5. How to get the object of Class class
forName() method of Class class
Class c=Class.forName("Simple")
System.out.println(c.getName())
getClass() method of Object class
Class c=obj.getClass();
System.out.println(c.getName());
the .class syntax
Class c2 = Test.class;
System.out.println(c2.getName());
6. Reflection vs Metaprogramming
Metaprogramming is "programs which write programs". This includes programs
that read the text of programs (arguably including themselves but that is rather
rare), analyze that code, and make changes.
Reflection is the ability for a program to inquire about its own structure.
7. Why do we need reflection?
Examine an object’s class at runtime
Construct an object for a class at runtime
Examine a class’s field and method at runtime
Invoke any method of an object at runtime
9. Real Usage Example
Code analyzer tools
Eclipse (Other IDEs) auto completion of method names
Spring Framework for creating the beans
Parsing annotations by ORMs like hibernate entity
10. Somewhere I read this quote:
“When you will need reflection; you will know it”.
11. For live project example
https://github.com/NexThoughts/ReflectionDemo