13
Java Reflection

Java reflection

Embed Size (px)

Citation preview

Page 1: Java reflection

Java Reflection

Page 2: 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

Page 3: Java reflection

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”.

Page 4: Java reflection

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);

Page 5: Java reflection

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());

Page 6: Java reflection

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.

Page 7: Java reflection

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

Page 8: Java reflection

Demo

Page 9: Java reflection

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

Page 10: Java reflection

Somewhere I read this quote:

“When you will need reflection; you will know it”.

Page 11: Java reflection

For live project examplehttps://github.com/NexThoughts/ReflectionDemo

Page 13: Java reflection

Thanks You