java reflection
TRANSCRIPT
Java Reflection
Agenda
What is Reflection?
How to get the object Class class
Reflection vs Metaprogramming
Why do we need reflection?
Demo
Real Usage Examples
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”.
Example:// without reflectionFoo foo = new Foo();foo.hello();
// with reflectionObject 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);
How to get the object of Class classforName() method of Class class
Class c=Class.forName("Simple"); System.out.println(c.getName());
getClass() method of Object classClass c=obj.getClass(); System.out.println(c.getName());
the .class syntaxClass c2 = Test.class; System.out.println(c2.getName());
Reflection vs MetaprogrammingMetaprogramming 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.
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
Demo
Real Usage ExampleCode analyzer tools
Eclipse (Other IDEs) auto completion of method names
Spring Framework for creating the beans
Parsing annotations by ORMs like hibernate entity
Junit Testcases
Somewhere I read this quote:
“When you will need reflection; you will know it”.
For live project examplehttps://github.com/NexThoughts/ReflectionDemo
Referenceshttp://tutorials.jenkov.com/java-reflection/index.html
http://www.javatpoint.com/java-reflection
http://www.programmerinterview.com/index.php/java-questions/java-reflection-example/
http://howtodoinjava.com/core-java/annotations/complete-java-annotations-tutorial/
http://howtodoinjava.com/core-java/related-concepts/real-usage-examples-of-reflection-in-java/
Thanks You