Java reflection

Preview:

Citation preview

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

Thanks You

Recommended