Reflection CMSC 432. 2 Issues What is reflection History of reflection How to use reflection Myths about reflection Advanced reflection issues Improvements.

Slides:



Advertisements
Similar presentations
Using Java™ Technology Reflection to Improve Design
Advertisements

10/18/08 Matt Swatzell. What is Reflection?  Some Definitions….  Reflection is the process by which a program can modify its own behavior.  A program.
ITEC200 – Week03 Inheritance and Class Hierarchies.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Fall 2007CS 2251 Inheritance and Class Hierarchies Chapter 3.
Object Oriented System Development with VB .NET
Fall 2007CS 2251 Inheritance and Class Hierarchies Chapter 3.
© 2006 Pearson Addison-Wesley. All rights reserved4-1 Chapter 4 Data Abstraction: The Walls.
Stéphane Ducasse6.1 Essential Concepts Why OO? What is OO? What are the benefits? What are the KEY concepts? Basis for all the lectures.
Reflection (Reflexion in British English ) Mo Alkhafaji.
How is Java different from other languages Less than you think: –Java is an imperative language (like C++, Ada, C, Pascal) –Java is interpreted (like LISP,
Inheritance and Polymorphism Recitation – 10/(16,17)/2008 CS 180 Department of Computer Science, Purdue University.
How is Java different from other languages Less than you think: –Java is an imperative language (like C++, Ada, C, Pascal) –Java is interpreted (like LISP,
Chapter 7 - Generalization/Specialization and Inheritance1 Chapter 7 Generalization/Specialization and Inheritance.
C++ fundamentals.
Java Course Outline Kumar Harshit, USW. Course Description Teaches students to program using the Java programming language with the help of the Netbeans.
Principles of Computer Programming (using Java) Review Haidong Xue Summer 2011, at GSU.
Advanced Inheritance Concepts. In this chapter, we will cover: Creating and using abstract classes Using dynamic method binding Creating arrays of subclass.
Appendix A.2: Review of Java and Object-Oriented Programming: Part 2 “For the object-oriented project, remember that the primary unit of decomposition.
Programming Languages and Paradigms Object-Oriented Programming.
220 FINAL TEST REVIEW SESSION Omar Abdelwahab. INHERITANCE AND POLYMORPHISM Suppose you have a class FunClass with public methods show, tell, and smile.
MT311 Java Application Development and Programming Languages Li Tak Sing( 李德成 )
CISC6795: Spring Object-Oriented Programming: Polymorphism.
CSM-Java Programming-I Spring,2005 Objects and Classes Overview Lesson - 1.
(C) 2010 Pearson Education, Inc. All rights reserved. Java™ How to Program, 8/e.
Recap (önemli noktaları yinelemek) from last week Paradigm Kay’s Description Intro to Objects Messages / Interconnections Information Hiding Classes Inheritance.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Chapter 21 Generics 1. Generics - Overview Generic Methods specify a set of related methods Generic classes specify a set of related types Software reuse.
1 Module Objective & Outline Module Objective: After completing this Module, you will be able to, appreciate java as a programming language, write java.
The Reflection Lucielle Mendez Antonio Bologna.
The Java Programming Language
Java™ How to Program, 9/e Presented by: Dr. José M. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
Introduction to Object Oriented Programming CMSC 331.
Inheritance - Polymorphism ITI 1121 Nour El Kadri.
More on Hierarchies 1. When an object of a subclass is instantiated, is memory allocated for only the data members of the subclass or also for the members.
Patterns in programming1. 2 What are patterns? Answers to common design problems. A language used by developers –To discuss answers to design problems.
Introducing Allors Applications, Tools & Platform.
 All calls to method toString and earnings are resolved at execution time, based on the type of the object to which currentEmployee refers.  Known as.
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
1 CSCD 326 Data Structures I Software Design. 2 The Software Life Cycle 1. Specification 2. Design 3. Risk Analysis 4. Verification 5. Coding 6. Testing.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
(1) ICS 313: Programming Language Theory Chapter 12: Object Oriented Programming.
Object Oriented Programming
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 JSP Application Models.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
CSCE 314 Programming Languages Reflection Dr. Hyunyoung Lee 1.
COM S 228 Introduction to Data Structures Instructor: Ying Cai Department of Computer Science Iowa State University Office: Atanasoff.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Java Programming, Second Edition Chapter Twelve Advanced Inheritance Concepts.
Inheritance and Class Hierarchies Chapter 3. Chapter Objectives  To understand inheritance and how it facilitates code reuse  To understand how Java.
Chapter 11: Advanced Inheritance Concepts. Objectives Create and use abstract classes Use dynamic method binding Create arrays of subclass objects Use.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
Author: DoanNX Time: 45’.  OOP concepts  OOP in Java.
Lecture XII: Runtime Software Evolution CS 4593 Cloud-Oriented Big Data and Software Engineering.
Reflection Mehdi Einali Advanced Programming in Java 1.
CSCI-383 Object-Oriented Programming & Design Lecture 17.
 It is a pure oops language and a high level language.  It was developed at sun microsystems by James Gosling.
Data Structures and Algorithms in JAVA Chapter 2.
Class Inheritance Part II: Overriding and Polymorphism Corresponds with Chapter 10.
Chapter 7: Cloning and RTTI
Visit for more Learning Resources
Overriding Method.
Inheritance and Polymorphism
CSE 413, Autumn 2002 Programming Languages
Presentation on Object Oriented programming Topic
ATS Application Programming: Java Programming
Advanced Programming in Java
Week 6 Object-Oriented Programming (2): Polymorphism
Advanced Inheritance Concepts
Presentation transcript:

Reflection CMSC 432

2 Issues 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 1. J. R. Jackson, A. L. McClellan, Java™ 1.2 By Example, Sun Microsystems, M. Campione, et al, The Java™ Tutorial Continued, Addison Wesley, 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 Not the only definition  Introspection  Intercession

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

7 Example UML

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

11 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

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

13 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

14 Reflection (Introspection) in Java If permitted by security policy, the Java Reflection API can be used to:  Construct new class instances and arrays  Access and modify fields (attributes) of objects and classes  Invoke methods on objects and classes  Access and modify elements of arrays

15 Reflection (Introspection) in Java The Java Reflection API consists of:  The class java.lang.Class  The interface java.lang.reflect.Member  The class java.lang.reflect.Field  The class java.lang.reflect.Method  The class java.lang.reflect.Constructor  The class java.lang.reflect.Array  The class java.lang.reflect.Modifier  The class java.lang.reflect. AccessibleObject.

16 import java.lang.reflect.Field; public class Test6 { public static void main(String args[]) throws Exception { final Field fields[] = FieldTest.class.getDeclaredFields(); for (int i = 0; i < fields.length; ++i) { if ("privateString".equals(fields[i].getName())) { fields[i].setAccessible(true); System.out.println( fields[i].get(new FieldTest())); break; }

17 Reflection Applications (Java) Applications getting run-time information about objects, use:  getField[s]  getMethod[s]  getConstructor[s] Applications getting compile-time information about objects (at the level provided by.class files), use:  getDeclaredField[s]  getDeclaredMethod[s]  getDeclaredConstructor[s]

18 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

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

20 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

21 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

22 Use Reflection With Design Patterns Design patterns can benefit from reflection Reflection can …  Further decouple objects  Simplify and reduce maintenance

23 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

24 Factory Without Reflection

25 Factory With Reflection

26 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

27 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

28 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

29 Listener Without Reflection

30 Listener With Reflection protected ActionListener actionAdapter = new ActionListener () { final static Class[] emptyClass = new Class[] {}; final static Object[] emptyObject = new Object[] {}; public void actionPerformed (ActionEvent e) { try { Outer.this.getClass ().getMethod (e.getActionCommand (), emptyClass).invoke (Outher.this, emptyObject); // alternatively // Outer.class.getMethod (e.getActionCommand (), // emptyClass).invoke (Outer.this, emptyObject); } catch (Exception ee) { } } };

31 Capabilities Not Available Using Java 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

32 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… Reducing application footprint Placing behaviors where they belong  Extends the power of classic object-oriented design patterns

33 Benefits of Reflection Reflection provides…  High level of object decoupling  Reduced level of maintenance  Programs become… Flexible Extensible Pluggable  Software becomes “soft”

34 Java Reflection - What’s missing Reflection is ‘read only’  Cant add / modify fields, methods Implementation is not available  Program logic is not reflected Major performance impact  May be much slower then doing the same operations directly… Complex code

35 Reflection A system is reflective if it can inspect part of its execution state while it is running. Introspection only reads internal state, without modifying it (also called reification) Reflection enables modifying execution state, and thereby changing system semantics (e.g. Lisp)

36 Meta Object Protocols Reflection applied to Object-Oriented systems The description of how an object system works at a basic level is called a Meta Object Protocol. The ability to change meta-object protocol is a powerful way to modify an object system For example, examine (or change) inheritance hierarchy while running Examine (or change) how inheritance works  How method lookup is done in the class hierarchy  How methods are called Applications in debugging, customizing, separation of concerns (aspects) Invented in the context of Common Lisp Object System (CLOS).

37 References OOP - Reflection glang/handouts/Section7.5.ppt glang/handouts/Section7.5.ppt Using Java™ Technology Reflection to Improve Design ( se2c.uni.lu/tiki/se2c- bib_download.php?id=472 )se2c.uni.lu/tiki/se2c- bib_download.php?id=472 Reflection In Java ( /ru/ho.html ) /ru/ho.html