SlideShare a Scribd company logo
The Incredible Reflection
and there we go..!

●
●

Classes like Class, Method, etc..
A running program examining itself and it's environment..
Some reflective jargon & The definition

●

Metadata, MetaObjects, Introspection, etc..

●

Definition

○
○
○

The ability of a running program to examine itself and its software environment introspect, and behave accordingly.
This self-examination requires a self-representation - metadata.
In an OO world, metadata is organized into objects - metaobjects.
Feature set
Methods of Class for field introspection:
Field getField( String name)
Returns a Field object that represents the specified public member field of this class/interface.
Field[] getFields()
Returns an array of Field objects that represents all the accessible public fields of the this
class/interface.
Field[] getDeclaredField( String name )
Returns a Field object representing the specified declared field by this class/interface.
Field[] getDeclaredFields()
Returns an array of Field objects that represents all the that represents each field declared by this
class/interface.
Feature set cont.d..
Methods of Class for field introspection:
Class getType(), Class getDeclaringClass(), String getName(), int
getModifiers(), Object get( Object obj ), void set( Object obj, Object
value ),
On the similar lines, there are set of methods available for Method, Constructor & Annotations.
Hierarchy of members within reflection API:

Member

Method

Field

Constructor
Armoury..

●
●
●
●
●
●
●
●
●

java.lang.Class
java.lang.reflect.Array
java.lang.reflect.AccessibleObject
java.lang.reflect.Constructor
java.lang.reflect.Field
java.lang.reflect.Member
java.lang.reflect.Method
java.lang.reflect.Modifier
java.lang.reflect.Proxy

- And many more..
Loading & Constructing at will..(1 of 2)
●

●

What web servers do?
○ loading and executing new code..
Load at will

○

Class.forname(String className)

■

Doesn't require class name at compile time

●

Examples:

○
○

Class cls = Class.forName("java.lang.String")
Class cls = Class.forName("java.lang.String[]");

■

System.out.println(String[].class.getName());
- Prints [Ljava.lang.String;

○
○
○

Class cls = Class.forName("[Ljava.lang.String;");
Will primitives work..?
Will primitive arrays work..?
Loading & Constructing at will..(2 of 2)

●

Reflective Construction

○

Class.newInstance()

■
○

Doesn't require class name at compile time

java.lang.reflect.Constructor

■

cls.getConstructor( new Class[] {String.class, String.class} )

●

introspects for a constructor of cls Class that takes two String parameters.

Flavours:
getConstructor(Class[]), getDeclaredConstructor(Class[]),
getConstructors(), getDeclaredConstructors()

○

Constructing Arrays

■
■
■
■

Array.newInstance()
Array.newInstance(String.class, 5);
Array.newInstance(String[].class, 5);
Array.newInstance(String.class, new int[] {2, 3});
The Joy of Breaking the laws..
#1

Accessing nonpublic members

Output:
Executing private method
120
The Joy of Breaking the laws..
#2

Breaking Immutability:

Output:
rue
String is mutable
String is mutable
Back to reality..
Plugging in the security module - SecurityManager
- An object that defines a security policy for an application.
- Any action not allowed in the policy throws SecurityException .
- Application can query its security manager for allowed actions
- Default policy file location : java.homelibsecurityjava.policy

- Specifying additional policy file at run time:
java -Djava.security.manager -Djava.security.policy=someURL SomeApp
Mastering the cross cutting issues..
What are cross cutting issues in an application?
Business flow Vs Logging
Business flow Vs Exception Handling
Business flow Vs Atomicity
Aspect Oriented Programming
Increasing modularity by allowing separation of cross cutting concerns

Logging
Exception Handling

Logging

Synchronizing
Business Logic

Synchronizing

Exception Handling

Business Logic
Dynamic Proxy
The Players:
java.lang.reflect.Proxy
- dynamic proxy-creation facility
Has methods to create a class that can work as a proxy
for another class.
Proxy instance provided, can implement the interfaces
implemented by the actual class; the class for which it
acts as a proxy.
java.lang.reflect.InvocationHandler - Each proxy instance has an associated invocation handler.
When a method is invoked on a proxy instance, the method invocation is encoded and dispatched to the invoke
method of its invocation handler.
Object InvocationHandler.invoke(Object proxy, Method method, Object[] args)
throws Throwable
method - the Method instance corresponding to the interface method invoked on the proxy instance.
args - an array of objects containing the values of the arguments passed in the method invocation on the proxy
instance.
=> Proxy can provide a Class or an instance that implements a given set of interfaces, of which every method call
is intercepted and provided with an opportunity to do some something extra..
Call Stacks & Stack Frames 1 of 2
- Each thread of execution has a call stack consisting of stack frames.
- Each frame in the call stack represents a method call.

Call Stack

Stack Frames
- Stack frames contain information pertinent to the
associated method.
- Each new method call corresponds to a new stack frame.
- Frame at the bottom of a call stack will be
main() or run()

StackTraceElement[] java.lang.Throwable.getStackTrace()
- new Throwable().getStackTrace()
- returns StackFrames Since the main() or run()
StackTraceElement provides following details:
File name, Line number, Class name, method name
Call Stacks & Stack Frames 2 of 2
Uses:
1.

Logging

2.

Security - Based on the caller's package or class access can be denied
new Throwable().getStackTrace()[1] = ?

Sample Usage:
main()

method1()

method2()

method3()

{

{

{

{

#16

m1(); #27

}

}

m2(); #38 m3() ; #56 StackTraceElement[] elt = new Throwable().getStackTrace();
}

}

Output:
elt[0] = Class : call.stack.introspection.CallStack1SampleApp File : CallStack1SampleApp.java Line : 56 Method :
method3
elt[1] = Class : call.stack.introspection.CallStack1SampleApp File : CallStack1SampleApp.java Line : 37 Method :
method2
elt[2] = Class : call.stack.introspection.CallStack1SampleApp File : CallStack1SampleApp.java Line : 27 Method :
method1
elt[3] = Class : call.stack.introspection.CallStack1SampleApp File : CallStack1SampleApp.java Line : 16 Method :
main
Is performance overstated?
"We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil. Yet
we should not pass up our opportunities in that critical 3%. A good programmer will not be lulled into complacency by
such reasoning, he will be wise to look carefully at the critical code; but only after that code has been identified"
— Donald Knuth

Reflective flexibility = Binding the names on run time..
●

Categorizing performance impact:
○ Construction overhead - One time
■ Dependency injection (Spring)
■ Dynamic Proxy for specific methods
■ Reflective code generation
○

○

●

Execution Overhead
■ Method.invoke()
■ Forwarding method through a proxy.
Granularity Overhead
■ Method.invoke() end up doing a lot of unnecessary checks

Granularity overheads should be narrowed whenever possible.
Through the JDKs..
●

JDK 1.0

○

●

Class, Object, ClassLoader
JDK1.1

○

●

java.lang.reflect, Field, Method, Constructor
JDK1.2

○

●

●
●
●

●

AccessibleObject, ReflectPermission
JDK1.3
○ Proxy, InvocationHandler, UndeclaredThrowableException,
InvocationTargetException
JDK1.4
○ StackTraceElement
JDK1.5
○ Generics support, Annotations
JDK1.6
○ 'Generified' some methods in Class: getInterfaces(), getClasses() , etc
○ The final parameter of Array.newInstance(Class, int...) is of variable arity.
JDK7
○ ReflectiveOperationException - A "Common superclass of exceptions thrown by reflective
operations in core reflection.
References
'Standing on the shoulders of giants'
Java Reflection in Action (In Action series) - Ira Forman and Nate Forman
http://www.javaworld.com/javaworld/jw-09-1997/jw-09-indepth.html?page=1
http://java.sun.com/developer/technicalArticles/ALT/Reflection/
http://docs.oracle.com/javase/tutorial/essential/environment/security.html
http://docs.oracle.com/javase/1.4.2/docs/guide/security/PolicyFiles.html
http://docs.oracle.com/javase/tutorial/reflect/TOC.html
http://java.sun.com/developer/technicalArticles/DynTypeLang/
http://stackoverflow.com/
Appendix 1

More Related Content

PDF
Java Reflection Explained Simply
PPT
Reflection in java
PPT
Java Reflection
PPT
Reflection
PDF
Advanced Reflection in Java
PDF
Basics of reflection in java
PPTX
Reflection in Java
PPTX
Java Reflection @KonaTechAdda
Java Reflection Explained Simply
Reflection in java
Java Reflection
Reflection
Advanced Reflection in Java
Basics of reflection in java
Reflection in Java
Java Reflection @KonaTechAdda

What's hot (20)

PPTX
Java reflection
PPTX
Java Reflection Concept and Working
PPTX
Introduction to Ruby’s Reflection API
PPT
Object Oriented Programming with Java
PPTX
Java interview questions 1
DOCX
Core java notes with examples
PPT
Most Asked Java Interview Question and Answer
PPT
Java API, Exceptions and IO
PDF
Understanding And Using Reflection
PPTX
Statics in java | Constructors | Exceptions in Java | String in java| class 3
PPT
Java Tutorial
DOCX
JAVA Notes - All major concepts covered with examples
PPT
9781111530532 ppt ch10
PDF
Access modifiers
PPS
Interface
PDF
Reflection in Ruby
PPTX
Object+oriented+programming+in+java
PDF
Object Oriented Programming using JAVA Notes
DOCX
Basic java important interview questions and answers to secure a job
PPTX
oops concept in java | object oriented programming in java
Java reflection
Java Reflection Concept and Working
Introduction to Ruby’s Reflection API
Object Oriented Programming with Java
Java interview questions 1
Core java notes with examples
Most Asked Java Interview Question and Answer
Java API, Exceptions and IO
Understanding And Using Reflection
Statics in java | Constructors | Exceptions in Java | String in java| class 3
Java Tutorial
JAVA Notes - All major concepts covered with examples
9781111530532 ppt ch10
Access modifiers
Interface
Reflection in Ruby
Object+oriented+programming+in+java
Object Oriented Programming using JAVA Notes
Basic java important interview questions and answers to secure a job
oops concept in java | object oriented programming in java
Ad

Similar to Java reflection (20)

PPT
Java class
PPT
Visula C# Programming Lecture 6
PPTX
CJP Unit-1 contd.pptx
PDF
Java Programming - 04 object oriented in java
PPT
9781439035665 ppt ch08
PDF
Advanced java jee material by KV Rao sir
PPT
Software Design Patterns
PPTX
Java basic part 2 : Datatypes Keywords Features Components Security Exceptions
PPTX
C# classes objects
PDF
Advance java kvr -satya
PDF
Adv kvr -satya
PPT
Chap08
DOCX
Diifeerences In C#
PPT
Core java by a introduction sandesh sharma
PPTX
Chap-2 Classes & Methods.pptx
PPT
JAVA CONCEPTS
PPTX
CS244 _Lec8_Generics_innerclasses_Lambda.pptx
PPTX
Lecture-Midterm .pptx
PDF
Programming II hiding, and .pdf
PPTX
object oriented programming using java, second sem BCA,UoM
Java class
Visula C# Programming Lecture 6
CJP Unit-1 contd.pptx
Java Programming - 04 object oriented in java
9781439035665 ppt ch08
Advanced java jee material by KV Rao sir
Software Design Patterns
Java basic part 2 : Datatypes Keywords Features Components Security Exceptions
C# classes objects
Advance java kvr -satya
Adv kvr -satya
Chap08
Diifeerences In C#
Core java by a introduction sandesh sharma
Chap-2 Classes & Methods.pptx
JAVA CONCEPTS
CS244 _Lec8_Generics_innerclasses_Lambda.pptx
Lecture-Midterm .pptx
Programming II hiding, and .pdf
object oriented programming using java, second sem BCA,UoM
Ad

Recently uploaded (20)

PPTX
GDM (1) (1).pptx small presentation for students
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PDF
Supply Chain Operations Speaking Notes -ICLT Program
PDF
Microbial disease of the cardiovascular and lymphatic systems
PPTX
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
PPTX
Cell Structure & Organelles in detailed.
PPTX
Cell Types and Its function , kingdom of life
PDF
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
PDF
Basic Mud Logging Guide for educational purpose
PDF
Sports Quiz easy sports quiz sports quiz
PDF
O7-L3 Supply Chain Operations - ICLT Program
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PPTX
Pharma ospi slides which help in ospi learning
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PDF
Insiders guide to clinical Medicine.pdf
PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PPTX
master seminar digital applications in india
PDF
TR - Agricultural Crops Production NC III.pdf
GDM (1) (1).pptx small presentation for students
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
Supply Chain Operations Speaking Notes -ICLT Program
Microbial disease of the cardiovascular and lymphatic systems
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
Cell Structure & Organelles in detailed.
Cell Types and Its function , kingdom of life
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
Basic Mud Logging Guide for educational purpose
Sports Quiz easy sports quiz sports quiz
O7-L3 Supply Chain Operations - ICLT Program
2.FourierTransform-ShortQuestionswithAnswers.pdf
Pharma ospi slides which help in ospi learning
Microbial diseases, their pathogenesis and prophylaxis
Pharmacology of Heart Failure /Pharmacotherapy of CHF
Insiders guide to clinical Medicine.pdf
102 student loan defaulters named and shamed – Is someone you know on the list?
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
master seminar digital applications in india
TR - Agricultural Crops Production NC III.pdf

Java reflection

  • 2. and there we go..! ● ● Classes like Class, Method, etc.. A running program examining itself and it's environment..
  • 3. Some reflective jargon & The definition ● Metadata, MetaObjects, Introspection, etc.. ● Definition ○ ○ ○ The ability of a running program to examine itself and its software environment introspect, and behave accordingly. This self-examination requires a self-representation - metadata. In an OO world, metadata is organized into objects - metaobjects.
  • 4. Feature set Methods of Class for field introspection: Field getField( String name) Returns a Field object that represents the specified public member field of this class/interface. Field[] getFields() Returns an array of Field objects that represents all the accessible public fields of the this class/interface. Field[] getDeclaredField( String name ) Returns a Field object representing the specified declared field by this class/interface. Field[] getDeclaredFields() Returns an array of Field objects that represents all the that represents each field declared by this class/interface.
  • 5. Feature set cont.d.. Methods of Class for field introspection: Class getType(), Class getDeclaringClass(), String getName(), int getModifiers(), Object get( Object obj ), void set( Object obj, Object value ), On the similar lines, there are set of methods available for Method, Constructor & Annotations. Hierarchy of members within reflection API: Member Method Field Constructor
  • 7. Loading & Constructing at will..(1 of 2) ● ● What web servers do? ○ loading and executing new code.. Load at will ○ Class.forname(String className) ■ Doesn't require class name at compile time ● Examples: ○ ○ Class cls = Class.forName("java.lang.String") Class cls = Class.forName("java.lang.String[]"); ■ System.out.println(String[].class.getName()); - Prints [Ljava.lang.String; ○ ○ ○ Class cls = Class.forName("[Ljava.lang.String;"); Will primitives work..? Will primitive arrays work..?
  • 8. Loading & Constructing at will..(2 of 2) ● Reflective Construction ○ Class.newInstance() ■ ○ Doesn't require class name at compile time java.lang.reflect.Constructor ■ cls.getConstructor( new Class[] {String.class, String.class} ) ● introspects for a constructor of cls Class that takes two String parameters. Flavours: getConstructor(Class[]), getDeclaredConstructor(Class[]), getConstructors(), getDeclaredConstructors() ○ Constructing Arrays ■ ■ ■ ■ Array.newInstance() Array.newInstance(String.class, 5); Array.newInstance(String[].class, 5); Array.newInstance(String.class, new int[] {2, 3});
  • 9. The Joy of Breaking the laws.. #1 Accessing nonpublic members Output: Executing private method 120
  • 10. The Joy of Breaking the laws.. #2 Breaking Immutability: Output: rue String is mutable String is mutable
  • 11. Back to reality.. Plugging in the security module - SecurityManager - An object that defines a security policy for an application. - Any action not allowed in the policy throws SecurityException . - Application can query its security manager for allowed actions - Default policy file location : java.homelibsecurityjava.policy - Specifying additional policy file at run time: java -Djava.security.manager -Djava.security.policy=someURL SomeApp
  • 12. Mastering the cross cutting issues.. What are cross cutting issues in an application? Business flow Vs Logging Business flow Vs Exception Handling Business flow Vs Atomicity Aspect Oriented Programming Increasing modularity by allowing separation of cross cutting concerns Logging Exception Handling Logging Synchronizing Business Logic Synchronizing Exception Handling Business Logic
  • 13. Dynamic Proxy The Players: java.lang.reflect.Proxy - dynamic proxy-creation facility Has methods to create a class that can work as a proxy for another class. Proxy instance provided, can implement the interfaces implemented by the actual class; the class for which it acts as a proxy. java.lang.reflect.InvocationHandler - Each proxy instance has an associated invocation handler. When a method is invoked on a proxy instance, the method invocation is encoded and dispatched to the invoke method of its invocation handler. Object InvocationHandler.invoke(Object proxy, Method method, Object[] args) throws Throwable method - the Method instance corresponding to the interface method invoked on the proxy instance. args - an array of objects containing the values of the arguments passed in the method invocation on the proxy instance. => Proxy can provide a Class or an instance that implements a given set of interfaces, of which every method call is intercepted and provided with an opportunity to do some something extra..
  • 14. Call Stacks & Stack Frames 1 of 2 - Each thread of execution has a call stack consisting of stack frames. - Each frame in the call stack represents a method call. Call Stack Stack Frames - Stack frames contain information pertinent to the associated method. - Each new method call corresponds to a new stack frame. - Frame at the bottom of a call stack will be main() or run() StackTraceElement[] java.lang.Throwable.getStackTrace() - new Throwable().getStackTrace() - returns StackFrames Since the main() or run() StackTraceElement provides following details: File name, Line number, Class name, method name
  • 15. Call Stacks & Stack Frames 2 of 2 Uses: 1. Logging 2. Security - Based on the caller's package or class access can be denied new Throwable().getStackTrace()[1] = ? Sample Usage: main() method1() method2() method3() { { { { #16 m1(); #27 } } m2(); #38 m3() ; #56 StackTraceElement[] elt = new Throwable().getStackTrace(); } } Output: elt[0] = Class : call.stack.introspection.CallStack1SampleApp File : CallStack1SampleApp.java Line : 56 Method : method3 elt[1] = Class : call.stack.introspection.CallStack1SampleApp File : CallStack1SampleApp.java Line : 37 Method : method2 elt[2] = Class : call.stack.introspection.CallStack1SampleApp File : CallStack1SampleApp.java Line : 27 Method : method1 elt[3] = Class : call.stack.introspection.CallStack1SampleApp File : CallStack1SampleApp.java Line : 16 Method : main
  • 16. Is performance overstated? "We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil. Yet we should not pass up our opportunities in that critical 3%. A good programmer will not be lulled into complacency by such reasoning, he will be wise to look carefully at the critical code; but only after that code has been identified" — Donald Knuth Reflective flexibility = Binding the names on run time.. ● Categorizing performance impact: ○ Construction overhead - One time ■ Dependency injection (Spring) ■ Dynamic Proxy for specific methods ■ Reflective code generation ○ ○ ● Execution Overhead ■ Method.invoke() ■ Forwarding method through a proxy. Granularity Overhead ■ Method.invoke() end up doing a lot of unnecessary checks Granularity overheads should be narrowed whenever possible.
  • 17. Through the JDKs.. ● JDK 1.0 ○ ● Class, Object, ClassLoader JDK1.1 ○ ● java.lang.reflect, Field, Method, Constructor JDK1.2 ○ ● ● ● ● ● AccessibleObject, ReflectPermission JDK1.3 ○ Proxy, InvocationHandler, UndeclaredThrowableException, InvocationTargetException JDK1.4 ○ StackTraceElement JDK1.5 ○ Generics support, Annotations JDK1.6 ○ 'Generified' some methods in Class: getInterfaces(), getClasses() , etc ○ The final parameter of Array.newInstance(Class, int...) is of variable arity. JDK7 ○ ReflectiveOperationException - A "Common superclass of exceptions thrown by reflective operations in core reflection.
  • 18. References 'Standing on the shoulders of giants' Java Reflection in Action (In Action series) - Ira Forman and Nate Forman http://www.javaworld.com/javaworld/jw-09-1997/jw-09-indepth.html?page=1 http://java.sun.com/developer/technicalArticles/ALT/Reflection/ http://docs.oracle.com/javase/tutorial/essential/environment/security.html http://docs.oracle.com/javase/1.4.2/docs/guide/security/PolicyFiles.html http://docs.oracle.com/javase/tutorial/reflect/TOC.html http://java.sun.com/developer/technicalArticles/DynTypeLang/ http://stackoverflow.com/