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

What's hot

Java reflection
Java reflectionJava reflection
Java reflection
NexThoughts Technologies
 
Java Reflection Concept and Working
Java Reflection Concept and WorkingJava Reflection Concept and Working
Java Reflection Concept and Working
Software Productivity Strategists, Inc
 
Introduction to Ruby’s Reflection API
Introduction to Ruby’s Reflection APIIntroduction to Ruby’s Reflection API
Introduction to Ruby’s Reflection API
Niranjan Sarade
 
Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with Javabackdoor
 
Java interview questions 1
Java interview questions 1Java interview questions 1
Java interview questions 1
Sherihan Anver
 
Core java notes with examples
Core java notes with examplesCore java notes with examples
Core java notes with examples
bindur87
 
Most Asked Java Interview Question and Answer
Most Asked Java Interview Question and AnswerMost Asked Java Interview Question and Answer
Most Asked Java Interview Question and Answer
TOPS Technologies
 
Understanding And Using Reflection
Understanding And Using ReflectionUnderstanding And Using Reflection
Understanding And Using ReflectionGanesh Samarthyam
 
Statics in java | Constructors | Exceptions in Java | String in java| class 3
Statics in java | Constructors | Exceptions in Java | String in java| class 3Statics in java | Constructors | Exceptions in Java | String in java| class 3
Statics in java | Constructors | Exceptions in Java | String in java| class 3
Sagar Verma
 
Java Tutorial
Java TutorialJava Tutorial
Java Tutorial
Singsys Pte Ltd
 
JAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examplesJAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examplesSunil Kumar Gunasekaran
 
9781111530532 ppt ch10
9781111530532 ppt ch109781111530532 ppt ch10
9781111530532 ppt ch10Terry Yoast
 
Access modifiers
Access modifiersAccess modifiers
Access modifiers
Kasun Ranga Wijeweera
 
Interface
InterfaceInterface
Interface
kamal kotecha
 
Reflection in Ruby
Reflection in RubyReflection in Ruby
Reflection in Ruby
kim.mens
 
Object+oriented+programming+in+java
Object+oriented+programming+in+javaObject+oriented+programming+in+java
Object+oriented+programming+in+java
Ye Win
 
Object Oriented Programming using JAVA Notes
Object Oriented Programming using JAVA Notes Object Oriented Programming using JAVA Notes
Object Oriented Programming using JAVA Notes
Uzair Salman
 
Basic java important interview questions and answers to secure a job
Basic java important interview questions and answers to secure a jobBasic java important interview questions and answers to secure a job
Basic java important interview questions and answers to secure a job
Garuda Trainings
 
oops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaoops concept in java | object oriented programming in java
oops concept in java | object oriented programming in java
CPD INDIA
 

What's hot (20)

Java reflection
Java reflectionJava reflection
Java reflection
 
Java Reflection Concept and Working
Java Reflection Concept and WorkingJava Reflection Concept and Working
Java Reflection Concept and Working
 
Introduction to Ruby’s Reflection API
Introduction to Ruby’s Reflection APIIntroduction to Ruby’s Reflection API
Introduction to Ruby’s Reflection API
 
Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with Java
 
Java interview questions 1
Java interview questions 1Java interview questions 1
Java interview questions 1
 
Core java notes with examples
Core java notes with examplesCore java notes with examples
Core java notes with examples
 
Most Asked Java Interview Question and Answer
Most Asked Java Interview Question and AnswerMost Asked Java Interview Question and Answer
Most Asked Java Interview Question and Answer
 
Java API, Exceptions and IO
Java API, Exceptions and IOJava API, Exceptions and IO
Java API, Exceptions and IO
 
Understanding And Using Reflection
Understanding And Using ReflectionUnderstanding And Using Reflection
Understanding And Using Reflection
 
Statics in java | Constructors | Exceptions in Java | String in java| class 3
Statics in java | Constructors | Exceptions in Java | String in java| class 3Statics in java | Constructors | Exceptions in Java | String in java| class 3
Statics in java | Constructors | Exceptions in Java | String in java| class 3
 
Java Tutorial
Java TutorialJava Tutorial
Java Tutorial
 
JAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examplesJAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examples
 
9781111530532 ppt ch10
9781111530532 ppt ch109781111530532 ppt ch10
9781111530532 ppt ch10
 
Access modifiers
Access modifiersAccess modifiers
Access modifiers
 
Interface
InterfaceInterface
Interface
 
Reflection in Ruby
Reflection in RubyReflection in Ruby
Reflection in Ruby
 
Object+oriented+programming+in+java
Object+oriented+programming+in+javaObject+oriented+programming+in+java
Object+oriented+programming+in+java
 
Object Oriented Programming using JAVA Notes
Object Oriented Programming using JAVA Notes Object Oriented Programming using JAVA Notes
Object Oriented Programming using JAVA Notes
 
Basic java important interview questions and answers to secure a job
Basic java important interview questions and answers to secure a jobBasic java important interview questions and answers to secure a job
Basic java important interview questions and answers to secure a job
 
oops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaoops concept in java | object oriented programming in java
oops concept in java | object oriented programming in java
 

Similar to Java reflection

Java class
Java classJava class
Java class
Arati Gadgil
 
Visula C# Programming Lecture 6
Visula C# Programming Lecture 6Visula C# Programming Lecture 6
Visula C# Programming Lecture 6
Abou Bakr Ashraf
 
CJP Unit-1 contd.pptx
CJP Unit-1 contd.pptxCJP Unit-1 contd.pptx
CJP Unit-1 contd.pptx
RAJASEKHARV10
 
Java Programming - 04 object oriented in java
Java Programming - 04 object oriented in javaJava Programming - 04 object oriented in java
Java Programming - 04 object oriented in java
Danairat Thanabodithammachari
 
9781439035665 ppt ch08
9781439035665 ppt ch089781439035665 ppt ch08
9781439035665 ppt ch08Terry Yoast
 
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sirAdvanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sir
AVINASH KUMAR
 
Software Design Patterns
Software Design PatternsSoftware Design Patterns
Software Design Patterns
Pankhuree Srivastava
 
Java basic part 2 : Datatypes Keywords Features Components Security Exceptions
Java basic part 2 : Datatypes Keywords Features Components Security Exceptions Java basic part 2 : Datatypes Keywords Features Components Security Exceptions
Java basic part 2 : Datatypes Keywords Features Components Security Exceptions
Soumen Santra
 
C# classes objects
C#  classes objectsC#  classes objects
C# classes objects
Dr.Neeraj Kumar Pandey
 
Adv kvr -satya
Adv  kvr -satyaAdv  kvr -satya
Adv kvr -satya
Jyothsna Sree
 
Advance java kvr -satya
Advance java  kvr -satyaAdvance java  kvr -satya
Advance java kvr -satya
Satya Johnny
 
Diifeerences In C#
Diifeerences In C#Diifeerences In C#
Diifeerences In C#
rohit_gupta_mrt
 
Core java by a introduction sandesh sharma
Core java by a introduction sandesh sharmaCore java by a introduction sandesh sharma
Core java by a introduction sandesh sharma
Sandesh Sharma
 
Chap-2 Classes & Methods.pptx
Chap-2 Classes & Methods.pptxChap-2 Classes & Methods.pptx
Chap-2 Classes & Methods.pptx
chetanpatilcp783
 
JAVA CONCEPTS
JAVA CONCEPTS JAVA CONCEPTS
JAVA CONCEPTS
Shivam Singh
 
CS244 _Lec8_Generics_innerclasses_Lambda.pptx
CS244 _Lec8_Generics_innerclasses_Lambda.pptxCS244 _Lec8_Generics_innerclasses_Lambda.pptx
CS244 _Lec8_Generics_innerclasses_Lambda.pptx
NadeemEzat
 
Programming II hiding, and .pdf
 Programming II hiding, and .pdf Programming II hiding, and .pdf
Programming II hiding, and .pdf
aludin007
 
object oriented programming using java, second sem BCA,UoM
object oriented programming using java, second sem BCA,UoMobject oriented programming using java, second sem BCA,UoM
object oriented programming using java, second sem BCA,UoM
ambikavenkatesh2
 
Desing pattern prototype-Factory Method, Prototype and Builder
Desing pattern prototype-Factory Method, Prototype and Builder Desing pattern prototype-Factory Method, Prototype and Builder
Desing pattern prototype-Factory Method, Prototype and Builder
paramisoft
 

Similar to Java reflection (20)

Java class
Java classJava class
Java class
 
Visula C# Programming Lecture 6
Visula C# Programming Lecture 6Visula C# Programming Lecture 6
Visula C# Programming Lecture 6
 
CJP Unit-1 contd.pptx
CJP Unit-1 contd.pptxCJP Unit-1 contd.pptx
CJP Unit-1 contd.pptx
 
Java Programming - 04 object oriented in java
Java Programming - 04 object oriented in javaJava Programming - 04 object oriented in java
Java Programming - 04 object oriented in java
 
9781439035665 ppt ch08
9781439035665 ppt ch089781439035665 ppt ch08
9781439035665 ppt ch08
 
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sirAdvanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sir
 
Software Design Patterns
Software Design PatternsSoftware Design Patterns
Software Design Patterns
 
Java basic part 2 : Datatypes Keywords Features Components Security Exceptions
Java basic part 2 : Datatypes Keywords Features Components Security Exceptions Java basic part 2 : Datatypes Keywords Features Components Security Exceptions
Java basic part 2 : Datatypes Keywords Features Components Security Exceptions
 
C# classes objects
C#  classes objectsC#  classes objects
C# classes objects
 
Adv kvr -satya
Adv  kvr -satyaAdv  kvr -satya
Adv kvr -satya
 
Advance java kvr -satya
Advance java  kvr -satyaAdvance java  kvr -satya
Advance java kvr -satya
 
Chap08
Chap08Chap08
Chap08
 
Diifeerences In C#
Diifeerences In C#Diifeerences In C#
Diifeerences In C#
 
Core java by a introduction sandesh sharma
Core java by a introduction sandesh sharmaCore java by a introduction sandesh sharma
Core java by a introduction sandesh sharma
 
Chap-2 Classes & Methods.pptx
Chap-2 Classes & Methods.pptxChap-2 Classes & Methods.pptx
Chap-2 Classes & Methods.pptx
 
JAVA CONCEPTS
JAVA CONCEPTS JAVA CONCEPTS
JAVA CONCEPTS
 
CS244 _Lec8_Generics_innerclasses_Lambda.pptx
CS244 _Lec8_Generics_innerclasses_Lambda.pptxCS244 _Lec8_Generics_innerclasses_Lambda.pptx
CS244 _Lec8_Generics_innerclasses_Lambda.pptx
 
Programming II hiding, and .pdf
 Programming II hiding, and .pdf Programming II hiding, and .pdf
Programming II hiding, and .pdf
 
object oriented programming using java, second sem BCA,UoM
object oriented programming using java, second sem BCA,UoMobject oriented programming using java, second sem BCA,UoM
object oriented programming using java, second sem BCA,UoM
 
Desing pattern prototype-Factory Method, Prototype and Builder
Desing pattern prototype-Factory Method, Prototype and Builder Desing pattern prototype-Factory Method, Prototype and Builder
Desing pattern prototype-Factory Method, Prototype and Builder
 

Recently uploaded

Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
MysoreMuleSoftMeetup
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
DeeptiGupta154
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Thiyagu K
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
siemaillard
 
How to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERPHow to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERP
Celine George
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
Vivekanand Anglo Vedic Academy
 
Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
Jisc
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
GeoBlogs
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
Balvir Singh
 
How to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS ModuleHow to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS Module
Celine George
 
The Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve ThomasonThe Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve Thomason
Steve Thomason
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
kaushalkr1407
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
Atul Kumar Singh
 
Ethnobotany and Ethnopharmacology ......
Ethnobotany and Ethnopharmacology ......Ethnobotany and Ethnopharmacology ......
Ethnobotany and Ethnopharmacology ......
Ashokrao Mane college of Pharmacy Peth-Vadgaon
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
Delapenabediema
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
EverAndrsGuerraGuerr
 
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptxStudents, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
EduSkills OECD
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
beazzy04
 
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
Nguyen Thanh Tu Collection
 
1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
JosvitaDsouza2
 

Recently uploaded (20)

Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 
How to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERPHow to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERP
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
 
Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
 
How to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS ModuleHow to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS Module
 
The Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve ThomasonThe Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve Thomason
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
 
Ethnobotany and Ethnopharmacology ......
Ethnobotany and Ethnopharmacology ......Ethnobotany and Ethnopharmacology ......
Ethnobotany and Ethnopharmacology ......
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
 
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptxStudents, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
 
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
 
1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
 

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/