SlideShare a Scribd company logo
Using Java™ Technology Reflection to Improve Design
Agenda What is reflection History of reflection How to use reflection Myths about reflection Advanced reflection issues Improvements to reflection Conclusion
What Is Reflection Java™ Technology provides two ways  to discover information about an object at runtime Traditional runtime class identification The object’s class is available at compile  and runtime Most commonly used Reflection The object’s class may not be available at compile or runtime
What Is Reflection “Reflection in a programming language context refers to the ability to observe and/or manipulate the inner workings of the environment programmatically.” 1 “The reflection API represents, or reflects, the classes, interfaces, and objects in the current Java™ virtual machine.” 2 1. J. R. Jackson, A. L. McClellan, Java™ 1.2 By Example, Sun Microsystems, 1999. 2. M. Campione, et al, The Java™ Tutorial Continued, Addison Wesley, 1999.
The History of Reflection Introduced in JDK™ 1.1 release to support the JavaBeans™ specification Used throughout the JDK™ software and Java runtime environment (JRE) Java™ Foundation Classes API (JFC) Jini™ connection technology JavaMail™ API JDBC™ API Improved in Java 1.2 SDK Further refined in Java 1.3 SDK
Why Runtime Class Identification Java™ technology takes advantage of polymorphism New subclasses easily added Bulk of behaviors inherited from  its superclass No impact on other subclasses of  the superclass At runtime, the JVM™ takes advantage  of late dynamic binding Messages are directed to the  correct method
Example UML
Runtime Class Identification Example Code Class loading occurs at first instantiation When the object is retrieved from the list, it is cast to the superclass,  Shape The object remembers its class and responds with the correct  draw  method
How the Class Object Works Every class loaded into the JVM™ has a Class object Corresponds to a .class file The ClassLoader is responsible for finding and loading the class into the JVM™ At object instantiation… The JVM™ checks to see if the class is already loaded into the virtual machine Locates and loads the class if necessary Once loaded, the JVM™ uses the loaded class to instantiate an instance
Proof of Dynamic Loading public static void main (String[] args) { System.out.println ("inside main"); new A (); System.out.println ("After creating A"); try { Class.forName ("B"); } catch (ClassNotFoundException e) { e.printStackTrace (); } System.out.println ("After forName (\"B\")"); new C (); System.out.println ("After creating C"); }
Late Dynamic Binding The JRE does not require that all classes are loaded prior to execution Different from most other environments   Class loading occurs when the class is first referenced Late Dynamic Binding is… Important for polymorphism Message propagation is dictated at runtime Messages are directed to the correct method Essential for reflection to be possible
Class Literals Using Class Literals is the second way to reference an object’s class Added in the JDK™ 1.1 release All classes, interfaces, arrays, and primitive types have class literals Primitive types have corresponding wrapper classes Examples: Triangle.CLASS int.TYPE
The  instanceof  Keyword The  instanceof  keyword is the third way to reference an object’s class Used with both classes and interfaces Returns true if the object is a species of a specified class Subclasses will also answer true Code becomes structurally bound to the class hierarchy Several limitations on the referenced class Must be a named class or interface The class constant cannot be the  Class  class Example: if (x  instanceof  Circle) ((Circle) x).setRadius (10);
The Reflection API The reflection API is the fourth way to reference an object’s class Reflection allows programs to interrogate and manipulate objects at runtime The reflected class may be… Unknown at compile time Dynamically loaded at runtime
Core Reflection Classes java.lang.reflect The reflection package Introduced in JDK 1.1 release java.lang.reflect.AccessibleObject The superclass for  Field ,  Method , and  Constructor  classes Suppresses the default Java language access control checks Introduced in JDK 1.2 release
Core Reflection Classes (Cont.) java.lang.reflect.Array Provides static methods to dynamically create and access Java arrays java.lang.reflect.Constructor Provides information about, and access to, a single constructor for a class
Core Reflection Classes (Cont.) java.lang.reflect.Field Provides information about, and dynamic access to, a single field of a class or  an interface The reflected field may be a class (static)  field or an instance field
Core Reflection Classes (Cont.) java.lang.reflect.Member Interface that reflects identifying information about a single member (a field or a method)  or a constructor java.lang.reflect.Method Provides information about, and access to, a single method on a class or interface   java.lang.reflect.Modifier Provides static methods and constants to decode class and member access modifiers
Core Reflection Classes (Cont.) JDK 1.3 release additions java.lang.reflect.Proxy Provides static methods for creating dynamic proxy classes and instances The superclass of all dynamic proxy classes created by those methods java.lang.reflect.InvocationHandler Interface Interface implemented by the invocation handler of a proxy instance
Commonly Used Classes java.lang.Class Represents classes and interfaces within a running Java™ technology-based program   java.lang.Package Provides information about a package that can be used to reflect upon a class or interface java.lang.ClassLoader An abstract class Provides class loader services
Using Reflection Reflection allows programs to interrogate an object at runtime without knowing the object’s class How can this be…  Connecting to a JavaBean™ technology- based component Object is not local RMI or serialized object Object dynamically injected
What Can I Do With Reflection Literally everything that you can do if you know the object’s class Load a class Determine if it is a class or interface Determine its superclass and implemented interfaces Instantiate a new instance of a class Determine class and instance methods Invoke class and instance methods Determine and possibly manipulate fields Determine the modifiers for fields, methods, classes,  and interfaces Etc.
Here Is How To… Load a class Class c = Class.forName (“Classname”) Determine if a class or interface c.isInterface ()  Determine lineage Superclass Class c1 = c.getSuperclass () Superinterface Class[] c2 = c.getInterfaces ()
Here Is How To… Determine implemented interfaces Class[] c2 = c.getInterfaces () Determine constructors Constructor[] c0 = c.getDeclaredConstructors () Instantiate an instance Default constructor Object o1 = c.newInstance () Non-default constructor Constructor c1 = c.getConstructor (class[]{…}) Object i = c1.newInstance (Object[] {…})
Here Is How To… Determine methods Methods[] m1 = c.getDeclaredMethods () Find a specific method Method m = c.getMethod (“methodName”,  new Class[] {…}) Invoke a method m.invoke (c, new Object[] {…})
Here Is How To… Determine modifiers Modifiers[] mo = c.getModifiers () Determine fields Class[] f = c.getDeclaredFields () Find a specific field Field f = c.getField() Modify a specific field Get the value of a specific field f.get (o) Set the value of a specific field f.set (o, value)
Four Myths of Reflection “ Reflection is only useful for JavaBeans™ technology-based components” “ Reflection is too complex for use in  general purpose applications” “ Reflection reduces performance  of applications” “ Reflection cannot be used with the 100% Pure Java™ certification standard”
“Reflection Is Only Useful for JavaBeans™ Technology-based Components” False Reflection is a common technique used in other pure object oriented languages like Smalltalk and Eiffel Benefits Reflection helps keep software robust Can help applications become more Flexible Extensible Pluggable
“Reflection Is Too Complex for Use in General Applications” False For most purposes, use of reflection requires mastery of only several method invocations The skills required are easily mastered Reflection can significantly… Reduce the footprint of an application Improve reusability
“Reflection Reduces the  Performance of Applications” False Reflection can actually increase the performance of code Benefits Can reduce and remove expensive conditional code Can simplify source code and design Can greatly expand the capabilities of the application
“Reflection Cannot Be Used With the 100% Pure Java™ Certification Standard” False There are some restrictions “The program must limit invocations to  classes that are part of the program or  part of the JRE” 3 3. Sun Microsystems, 100% Pure Java™ Certification Guide, version 3.1, May 2000.
Advanced Reflection Issues Why use reflection Using reflection with object-oriented design patterns Common problems solved using reflection Misuse of switch/case statements User interface listeners
Why Use Reflection Reflection solves problems within  object-oriented design: Flexibility Extensibility Pluggability Reflection solves problems  caused by… The static nature of the class hierarchy The complexities of strong typing
Use Reflection With Design Patterns Design patterns can benefit  from reflection Reflection can … Further decouple objects Simplify and reduce maintenance
Design Patterns and Reflection Many of the object- oriented design patterns can benefit from reflection Reflection extends  the decoupling of objects that design patterns offer Can significantly simplify design patterns Factory Factory Method State Command Observer Others
Factory Without Reflection
Factory With Reflection
Design Pattern Implications Product classes can be added, changed, or deleted without affecting the factory Faster development (one factory fits all) Reduced maintenance Less code to develop, test, and debug
Design Strategies for Using Reflection Challenge switch/case and cascading  if statements Rationale The switch statement should scream “redesign me” to the developer In most cases, switch statements perform pseudo subclass operations Steps Redesign using an appropriate class decomposition Eliminate the switch/case statement Consider a design pattern approach Benefits High level of object decoupling Reduced level of maintenance
Challenge UI Listeners Can a generalized listener function for several components or does each component need a unique listener? Consider using the Command design pattern Steps Use the  setActionCommand  method to set the method to reflect upon for each component Instantiate only one instant of the listener Benefits Smaller program memory footprint Faster performance due to less class loading Behavior placed in the appropriate place
Listener Without Reflection
Listener With Reflection
Improvements to Reflection  in JDK™ 1.2 Release Numerous small changes throughout  the API Most changes “under the hood” Two classes added AccessibleObject  class Allows trusted applications to work with private, protected, and default visibility members ReflectPermission  class Complements the  AccessibleObject  class Governs the access to objects and their components via reflection
Improvements to Reflection in JDK™ 1.3 Release Two significant additions to the API Proxy  Class Implements a specified list of interfaces Delegates invocation of the methods  defined by those interfaces to a separate  InvocationHandler  object InvocationHandler  Interface Defines a single invoke method that is  called whenever a method is invoked on  a dynamically created  Proxy  object
Capabilities Not Available Using Reflection What are a class’ subclasses? Not possible due to dynamic class loading What method is currently executing Not the purpose of reflection Other APIs provide this capability
Review The JRE allows 4 ways to reference a class The class’ class definition Class literals The  instanceof  keyword Reflection Reflection is the only pure runtime way Provides full access to the object’s capabilities  Provides runtime capabilities not  otherwise available Improves the quality of an application
Review Solves several design issues Simplifies the static complexity of methods by providing elimination of… Nested if/else constructs The switch/case construct Improves user interface code by… Removing redundant inner classes Reducing application footprint Placing behaviors where they belong Extends the power of classic  object-oriented design patterns
Benefits of Reflection Reflection provides… High level of object decoupling Reduced level of maintenance Programs become… Flexible Extensible Pluggable Software becomes “soft”

More Related Content

What's hot (20)

PPT
Design patterns ppt
Aman Jain
 
PPTX
Grasp patterns and its types
Syed Hassan Ali
 
PPT
Abstract class
Tony Nguyen
 
PDF
Oops concepts || Object Oriented Programming Concepts in Java
Madishetty Prathibha
 
PPTX
Java Beans
Ankit Desai
 
PPTX
Java Swing
Komal Gandhi
 
PPTX
Java packages
BHUVIJAYAVELU
 
PPT
JDBC – Java Database Connectivity
Information Technology
 
PPTX
Inner classes in java
PhD Research Scholar
 
PPTX
This keyword in java
Hitesh Kumar
 
PPTX
Common language runtime clr
SanSan149
 
PPTX
Java database connectivity with MySql
Dhyey Dattani
 
PDF
OOP and FP
Mario Fusco
 
PPS
Java Exception handling
kamal kotecha
 
PPTX
Web forms in ASP.net
Madhuri Kavade
 
PPTX
Operators in java
AbhishekMondal42
 
PDF
Remote Method Invocation (RMI)
Peter R. Egli
 
PPT
Java collections concept
kumar gaurav
 
PPT
Packages in java
Abhishek Khune
 
PPTX
Classes,object and methods java
Padma Kannan
 
Design patterns ppt
Aman Jain
 
Grasp patterns and its types
Syed Hassan Ali
 
Abstract class
Tony Nguyen
 
Oops concepts || Object Oriented Programming Concepts in Java
Madishetty Prathibha
 
Java Beans
Ankit Desai
 
Java Swing
Komal Gandhi
 
Java packages
BHUVIJAYAVELU
 
JDBC – Java Database Connectivity
Information Technology
 
Inner classes in java
PhD Research Scholar
 
This keyword in java
Hitesh Kumar
 
Common language runtime clr
SanSan149
 
Java database connectivity with MySql
Dhyey Dattani
 
OOP and FP
Mario Fusco
 
Java Exception handling
kamal kotecha
 
Web forms in ASP.net
Madhuri Kavade
 
Operators in java
AbhishekMondal42
 
Remote Method Invocation (RMI)
Peter R. Egli
 
Java collections concept
kumar gaurav
 
Packages in java
Abhishek Khune
 
Classes,object and methods java
Padma Kannan
 

Viewers also liked (20)

PDF
Basics of reflection in java
kim.mens
 
PPTX
Reflection in Java
Nikhil Bhardwaj
 
PDF
Java Reflection Explained Simply
Ciaran McHale
 
ODP
Supercharging reflective libraries with InvokeDynamic
Ian Robertson
 
PPS
Reflection Free Factories in Java
guesta045fd
 
PPTX
JAVA PROGRAMMING
Niyitegekabilly
 
PDF
Java reflection
Ranjith Chaz
 
DOCX
Final project digital artifact
mwanzui gabriel
 
PDF
Factory method pattern (Virtual Constructor)
Sameer Rathoud
 
KEY
Using Chef for Automated Infrastructure in the Cloud
Jesse Robbins
 
PPT
Experimental study of light reflection laws
mimibalan
 
PPT
Blackboard Pattern
tcab22
 
PPT
Java beans
Ramraj Choudhary
 
PDF
Reflection and Introspection
adil raja
 
PDF
Java Serialization
imypraz
 
PPT
Java-java virtual machine
Surbhi Panhalkar
 
PDF
Docker Introduction
Robert Reiz
 
PDF
javabeans
Arjun Shanka
 
PDF
Ansible - Introduction
Stephane Manciot
 
Basics of reflection in java
kim.mens
 
Reflection in Java
Nikhil Bhardwaj
 
Java Reflection Explained Simply
Ciaran McHale
 
Supercharging reflective libraries with InvokeDynamic
Ian Robertson
 
Reflection Free Factories in Java
guesta045fd
 
JAVA PROGRAMMING
Niyitegekabilly
 
Java reflection
Ranjith Chaz
 
Final project digital artifact
mwanzui gabriel
 
Factory method pattern (Virtual Constructor)
Sameer Rathoud
 
Using Chef for Automated Infrastructure in the Cloud
Jesse Robbins
 
Experimental study of light reflection laws
mimibalan
 
Blackboard Pattern
tcab22
 
Java beans
Ramraj Choudhary
 
Reflection and Introspection
adil raja
 
Java Serialization
imypraz
 
Java-java virtual machine
Surbhi Panhalkar
 
Docker Introduction
Robert Reiz
 
javabeans
Arjun Shanka
 
Ansible - Introduction
Stephane Manciot
 
Ad

Similar to Reflection in java (20)

PPTX
Java Reflection Concept and Working
Software Productivity Strategists, Inc
 
PDF
Understanding And Using Reflection
Ganesh Samarthyam
 
PPT
Reflection
Piyush Mittal
 
PDF
Java Reflection
Hamid Ghorbani
 
PPTX
Cuối cùng cũng đã chuẩn bị slide xong cho seminar ngày mai. Mai seminar đầu t...
Khoa Nguyen
 
PPT
Object and Classes in Java
backdoor
 
PPTX
Java Reflection @KonaTechAdda
Md Imran Hasan Hira
 
PPTX
Java reflection
NexThoughts Technologies
 
PDF
Pharo: a reflective language A first systematic analysis of reflective APIs
ESUG
 
PDF
Metaprograms and metadata (as part of the the PTT lecture)
Ralf Laemmel
 
PPT
Reflection in C Sharp
Harman Bajwa
 
PDF
Advanced java jee material by KV Rao sir
AVINASH KUMAR
 
PDF
Dynamic Proxy by Java
Kan-Han (John) Lu
 
PDF
Advance java kvr -satya
Satya Johnny
 
PDF
Adv kvr -satya
Jyothsna Sree
 
PPTX
Object Oriented Programming Tutorial.pptx
ethiouniverse
 
PPT
Smoke and Mirrors - Reflection in C#
Wekoslav Stefanovski
 
PPTX
Objects and classes in OO Programming concepts
researchveltech
 
PPTX
19 reflection
dhrubo kayal
 
PDF
Java Programming - 04 object oriented in java
Danairat Thanabodithammachari
 
Java Reflection Concept and Working
Software Productivity Strategists, Inc
 
Understanding And Using Reflection
Ganesh Samarthyam
 
Reflection
Piyush Mittal
 
Java Reflection
Hamid Ghorbani
 
Cuối cùng cũng đã chuẩn bị slide xong cho seminar ngày mai. Mai seminar đầu t...
Khoa Nguyen
 
Object and Classes in Java
backdoor
 
Java Reflection @KonaTechAdda
Md Imran Hasan Hira
 
Java reflection
NexThoughts Technologies
 
Pharo: a reflective language A first systematic analysis of reflective APIs
ESUG
 
Metaprograms and metadata (as part of the the PTT lecture)
Ralf Laemmel
 
Reflection in C Sharp
Harman Bajwa
 
Advanced java jee material by KV Rao sir
AVINASH KUMAR
 
Dynamic Proxy by Java
Kan-Han (John) Lu
 
Advance java kvr -satya
Satya Johnny
 
Adv kvr -satya
Jyothsna Sree
 
Object Oriented Programming Tutorial.pptx
ethiouniverse
 
Smoke and Mirrors - Reflection in C#
Wekoslav Stefanovski
 
Objects and classes in OO Programming concepts
researchveltech
 
19 reflection
dhrubo kayal
 
Java Programming - 04 object oriented in java
Danairat Thanabodithammachari
 
Ad

Recently uploaded (20)

PDF
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
PDF
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
PDF
“Computer Vision at Sea: Automated Fish Tracking for Sustainable Fishing,” a ...
Edge AI and Vision Alliance
 
PDF
NASA A Researcher’s Guide to International Space Station : Physical Sciences ...
Dr. PANKAJ DHUSSA
 
PPTX
Agentforce World Tour Toronto '25 - Supercharge MuleSoft Development with Mod...
Alexandra N. Martinez
 
PDF
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
DOCX
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
PDF
NLJUG Speaker academy 2025 - first session
Bert Jan Schrijver
 
PDF
Transcript: Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
PPTX
Designing_the_Future_AI_Driven_Product_Experiences_Across_Devices.pptx
presentifyai
 
PDF
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
PPTX
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
PDF
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
PDF
UiPath DevConnect 2025: Agentic Automation Community User Group Meeting
DianaGray10
 
PDF
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
PPTX
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
PDF
“Voice Interfaces on a Budget: Building Real-time Speech Recognition on Low-c...
Edge AI and Vision Alliance
 
PDF
SIZING YOUR AIR CONDITIONER---A PRACTICAL GUIDE.pdf
Muhammad Rizwan Akram
 
PDF
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
DOCX
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
“Computer Vision at Sea: Automated Fish Tracking for Sustainable Fishing,” a ...
Edge AI and Vision Alliance
 
NASA A Researcher’s Guide to International Space Station : Physical Sciences ...
Dr. PANKAJ DHUSSA
 
Agentforce World Tour Toronto '25 - Supercharge MuleSoft Development with Mod...
Alexandra N. Martinez
 
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
NLJUG Speaker academy 2025 - first session
Bert Jan Schrijver
 
Transcript: Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
Designing_the_Future_AI_Driven_Product_Experiences_Across_Devices.pptx
presentifyai
 
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
UiPath DevConnect 2025: Agentic Automation Community User Group Meeting
DianaGray10
 
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
“Voice Interfaces on a Budget: Building Real-time Speech Recognition on Low-c...
Edge AI and Vision Alliance
 
SIZING YOUR AIR CONDITIONER---A PRACTICAL GUIDE.pdf
Muhammad Rizwan Akram
 
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 

Reflection in java

  • 1. Using Java™ Technology Reflection to Improve Design
  • 2. Agenda What is reflection History of reflection How to use reflection Myths about reflection Advanced reflection issues Improvements to reflection Conclusion
  • 3. What Is Reflection Java™ Technology provides two ways to discover information about an object at runtime Traditional runtime class identification The object’s class is available at compile and runtime Most commonly used Reflection The object’s class may not be available at compile or runtime
  • 4. What Is Reflection “Reflection in a programming language context refers to the ability to observe and/or manipulate the inner workings of the environment programmatically.” 1 “The reflection API represents, or reflects, the classes, interfaces, and objects in the current Java™ virtual machine.” 2 1. J. R. Jackson, A. L. McClellan, Java™ 1.2 By Example, Sun Microsystems, 1999. 2. M. Campione, et al, The Java™ Tutorial Continued, Addison Wesley, 1999.
  • 5. The History of Reflection Introduced in JDK™ 1.1 release to support the JavaBeans™ specification Used throughout the JDK™ software and Java runtime environment (JRE) Java™ Foundation Classes API (JFC) Jini™ connection technology JavaMail™ API JDBC™ API Improved in Java 1.2 SDK Further refined in Java 1.3 SDK
  • 6. Why Runtime Class Identification Java™ technology takes advantage of polymorphism New subclasses easily added Bulk of behaviors inherited from its superclass No impact on other subclasses of the superclass At runtime, the JVM™ takes advantage of late dynamic binding Messages are directed to the correct method
  • 8. Runtime Class Identification Example Code Class loading occurs at first instantiation When the object is retrieved from the list, it is cast to the superclass, Shape The object remembers its class and responds with the correct draw method
  • 9. How the Class Object Works Every class loaded into the JVM™ has a Class object Corresponds to a .class file The ClassLoader is responsible for finding and loading the class into the JVM™ At object instantiation… The JVM™ checks to see if the class is already loaded into the virtual machine Locates and loads the class if necessary Once loaded, the JVM™ uses the loaded class to instantiate an instance
  • 10. Proof of Dynamic Loading public static void main (String[] args) { System.out.println ("inside main"); new A (); System.out.println ("After creating A"); try { Class.forName ("B"); } catch (ClassNotFoundException e) { e.printStackTrace (); } System.out.println ("After forName (\"B\")"); new C (); System.out.println ("After creating C"); }
  • 11. Late Dynamic Binding The JRE does not require that all classes are loaded prior to execution Different from most other environments Class loading occurs when the class is first referenced Late Dynamic Binding is… Important for polymorphism Message propagation is dictated at runtime Messages are directed to the correct method Essential for reflection to be possible
  • 12. Class Literals Using Class Literals is the second way to reference an object’s class Added in the JDK™ 1.1 release All classes, interfaces, arrays, and primitive types have class literals Primitive types have corresponding wrapper classes Examples: Triangle.CLASS int.TYPE
  • 13. The instanceof Keyword The instanceof keyword is the third way to reference an object’s class Used with both classes and interfaces Returns true if the object is a species of a specified class Subclasses will also answer true Code becomes structurally bound to the class hierarchy Several limitations on the referenced class Must be a named class or interface The class constant cannot be the Class class Example: if (x instanceof Circle) ((Circle) x).setRadius (10);
  • 14. The Reflection API The reflection API is the fourth way to reference an object’s class Reflection allows programs to interrogate and manipulate objects at runtime The reflected class may be… Unknown at compile time Dynamically loaded at runtime
  • 15. Core Reflection Classes java.lang.reflect The reflection package Introduced in JDK 1.1 release java.lang.reflect.AccessibleObject The superclass for Field , Method , and Constructor classes Suppresses the default Java language access control checks Introduced in JDK 1.2 release
  • 16. Core Reflection Classes (Cont.) java.lang.reflect.Array Provides static methods to dynamically create and access Java arrays java.lang.reflect.Constructor Provides information about, and access to, a single constructor for a class
  • 17. Core Reflection Classes (Cont.) java.lang.reflect.Field Provides information about, and dynamic access to, a single field of a class or an interface The reflected field may be a class (static) field or an instance field
  • 18. Core Reflection Classes (Cont.) java.lang.reflect.Member Interface that reflects identifying information about a single member (a field or a method) or a constructor java.lang.reflect.Method Provides information about, and access to, a single method on a class or interface java.lang.reflect.Modifier Provides static methods and constants to decode class and member access modifiers
  • 19. Core Reflection Classes (Cont.) JDK 1.3 release additions java.lang.reflect.Proxy Provides static methods for creating dynamic proxy classes and instances The superclass of all dynamic proxy classes created by those methods java.lang.reflect.InvocationHandler Interface Interface implemented by the invocation handler of a proxy instance
  • 20. Commonly Used Classes java.lang.Class Represents classes and interfaces within a running Java™ technology-based program java.lang.Package Provides information about a package that can be used to reflect upon a class or interface java.lang.ClassLoader An abstract class Provides class loader services
  • 21. Using Reflection Reflection allows programs to interrogate an object at runtime without knowing the object’s class How can this be… Connecting to a JavaBean™ technology- based component Object is not local RMI or serialized object Object dynamically injected
  • 22. What Can I Do With Reflection Literally everything that you can do if you know the object’s class Load a class Determine if it is a class or interface Determine its superclass and implemented interfaces Instantiate a new instance of a class Determine class and instance methods Invoke class and instance methods Determine and possibly manipulate fields Determine the modifiers for fields, methods, classes, and interfaces Etc.
  • 23. Here Is How To… Load a class Class c = Class.forName (“Classname”) Determine if a class or interface c.isInterface () Determine lineage Superclass Class c1 = c.getSuperclass () Superinterface Class[] c2 = c.getInterfaces ()
  • 24. Here Is How To… Determine implemented interfaces Class[] c2 = c.getInterfaces () Determine constructors Constructor[] c0 = c.getDeclaredConstructors () Instantiate an instance Default constructor Object o1 = c.newInstance () Non-default constructor Constructor c1 = c.getConstructor (class[]{…}) Object i = c1.newInstance (Object[] {…})
  • 25. Here Is How To… Determine methods Methods[] m1 = c.getDeclaredMethods () Find a specific method Method m = c.getMethod (“methodName”, new Class[] {…}) Invoke a method m.invoke (c, new Object[] {…})
  • 26. Here Is How To… Determine modifiers Modifiers[] mo = c.getModifiers () Determine fields Class[] f = c.getDeclaredFields () Find a specific field Field f = c.getField() Modify a specific field Get the value of a specific field f.get (o) Set the value of a specific field f.set (o, value)
  • 27. Four Myths of Reflection “ Reflection is only useful for JavaBeans™ technology-based components” “ Reflection is too complex for use in general purpose applications” “ Reflection reduces performance of applications” “ Reflection cannot be used with the 100% Pure Java™ certification standard”
  • 28. “Reflection Is Only Useful for JavaBeans™ Technology-based Components” False Reflection is a common technique used in other pure object oriented languages like Smalltalk and Eiffel Benefits Reflection helps keep software robust Can help applications become more Flexible Extensible Pluggable
  • 29. “Reflection Is Too Complex for Use in General Applications” False For most purposes, use of reflection requires mastery of only several method invocations The skills required are easily mastered Reflection can significantly… Reduce the footprint of an application Improve reusability
  • 30. “Reflection Reduces the Performance of Applications” False Reflection can actually increase the performance of code Benefits Can reduce and remove expensive conditional code Can simplify source code and design Can greatly expand the capabilities of the application
  • 31. “Reflection Cannot Be Used With the 100% Pure Java™ Certification Standard” False There are some restrictions “The program must limit invocations to classes that are part of the program or part of the JRE” 3 3. Sun Microsystems, 100% Pure Java™ Certification Guide, version 3.1, May 2000.
  • 32. Advanced Reflection Issues Why use reflection Using reflection with object-oriented design patterns Common problems solved using reflection Misuse of switch/case statements User interface listeners
  • 33. Why Use Reflection Reflection solves problems within object-oriented design: Flexibility Extensibility Pluggability Reflection solves problems caused by… The static nature of the class hierarchy The complexities of strong typing
  • 34. Use Reflection With Design Patterns Design patterns can benefit from reflection Reflection can … Further decouple objects Simplify and reduce maintenance
  • 35. Design Patterns and Reflection Many of the object- oriented design patterns can benefit from reflection Reflection extends the decoupling of objects that design patterns offer Can significantly simplify design patterns Factory Factory Method State Command Observer Others
  • 38. Design Pattern Implications Product classes can be added, changed, or deleted without affecting the factory Faster development (one factory fits all) Reduced maintenance Less code to develop, test, and debug
  • 39. Design Strategies for Using Reflection Challenge switch/case and cascading if statements Rationale The switch statement should scream “redesign me” to the developer In most cases, switch statements perform pseudo subclass operations Steps Redesign using an appropriate class decomposition Eliminate the switch/case statement Consider a design pattern approach Benefits High level of object decoupling Reduced level of maintenance
  • 40. Challenge UI Listeners Can a generalized listener function for several components or does each component need a unique listener? Consider using the Command design pattern Steps Use the setActionCommand method to set the method to reflect upon for each component Instantiate only one instant of the listener Benefits Smaller program memory footprint Faster performance due to less class loading Behavior placed in the appropriate place
  • 43. Improvements to Reflection in JDK™ 1.2 Release Numerous small changes throughout the API Most changes “under the hood” Two classes added AccessibleObject class Allows trusted applications to work with private, protected, and default visibility members ReflectPermission class Complements the AccessibleObject class Governs the access to objects and their components via reflection
  • 44. Improvements to Reflection in JDK™ 1.3 Release Two significant additions to the API Proxy Class Implements a specified list of interfaces Delegates invocation of the methods defined by those interfaces to a separate InvocationHandler object InvocationHandler Interface Defines a single invoke method that is called whenever a method is invoked on a dynamically created Proxy object
  • 45. Capabilities Not Available Using Reflection What are a class’ subclasses? Not possible due to dynamic class loading What method is currently executing Not the purpose of reflection Other APIs provide this capability
  • 46. Review The JRE allows 4 ways to reference a class The class’ class definition Class literals The instanceof keyword Reflection Reflection is the only pure runtime way Provides full access to the object’s capabilities Provides runtime capabilities not otherwise available Improves the quality of an application
  • 47. Review Solves several design issues Simplifies the static complexity of methods by providing elimination of… Nested if/else constructs The switch/case construct Improves user interface code by… Removing redundant inner classes Reducing application footprint Placing behaviors where they belong Extends the power of classic object-oriented design patterns
  • 48. Benefits of Reflection Reflection provides… High level of object decoupling Reduced level of maintenance Programs become… Flexible Extensible Pluggable Software becomes “soft”