Using Java™ Technology Reflection to Improve Design

Slides:



Advertisements
Similar presentations
ASSUMPTION HIERARCHY FOR A CHA CALL GRAPH CONSTRUCTION ALGORITHM JASON SAWIN & ATANAS ROUNTEV.
Advertisements

Inheritance Java permits you to use your user defined classes to create programs using inheritance.
Reflection CMSC Issues What is reflection History of reflection How to use reflection Myths about reflection Advanced reflection issues Improvements.
ITEC200 – Week03 Inheritance and Class Hierarchies.
Object-Oriented PHP (1)
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.
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Fall 2007CS 2251 Inheritance and Class Hierarchies Chapter 3.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
1 Inheritance and Polymorphism. 2 Motivations Suppose you will define classes to model circles, rectangles, and triangles. These classes have many common.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
Data Abstraction and Object- Oriented Programming CS351 – Programming Paradigms.
INTRODUCTION TO JAVA PROGRAMMING Chapter 1. What is Computer Programming?
1 Chapter 8 Objects and Classes. 2 Motivations After learning the preceding chapters, you are capable of solving many programming problems using selections,
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.
Programming Languages and Paradigms Object-Oriented Programming.
Chapter 6 Class Inheritance F Superclasses and Subclasses F Keywords: super F Overriding methods F The Object Class F Modifiers: protected, final and abstract.
1 Virtual Functions and Polymorphism Chapter What You Will Learn What is polymorphism? How to declare and use virtual functions for abstract classes.
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page 1 Virtual Functions Polymorphism Abstract base classes.
OOPs Object oriented programming. Based on ADT principles  Representation of type and operations in a single unit  Available for other units to create.
CISC6795: Spring Object-Oriented Programming: Polymorphism.
(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.
Lecture objectives  Differences between Java and C#  Understand and use abstract classes  Casting in Java: why is it important?  Master exceptions.
The Reflection Lucielle Mendez Antonio Bologna.
Java™ How to Program, 9/e Presented by: Dr. José M. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
Inheritance - Polymorphism ITI 1121 Nour El Kadri.
© Keren Kalif Advanced Java Topics Written by Keren Kalif, Edited by Liron Blecher.
Patterns in programming1. 2 What are patterns? Answers to common design problems. A language used by developers –To discuss answers to design problems.
Programming in Java CSCI-2220 Object Oriented Programming.
 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.
Summing Up Object Oriented Design. Four Major Components: Abstraction modeling real-life entities by essential information only Encapsulation clustering.
Lecture 10 Concepts of Programming Languages Arne Kutzner Hanyang University / Seoul Korea.
Introduction to Java Chapter 7 - Classes & Object-oriented Programming1 Chapter 7 Classes and Object-Oriented Programming.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Chapter 5 Objects and Classes Inheritance. Solution Assignments 3 & 4 Review in class…..
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 9 Inheritance and.
Object Oriented Programming
Design Patterns Software Engineering CS 561. Last Time Introduced design patterns Abstraction-Occurrence General Hierarchy Player-Role.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
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.
 2005 Pearson Education, Inc. All rights reserved. 1 Classes and Objects: A Deeper Look.
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.
C++ General Characteristics: - Mixed typing system - Constructors and destructors - Elaborate access controls to class entities.
Notices Assn 2 is due tomorrow, 7pm. Moodle quiz next week – written in the lab as before. Everything up to and including today’s lecture: Big Topics are.
Chapter 5 Introduction to Defining Classes Fundamentals of Java.
Java Programming: Guided Learning with Early Objects Chapter 9 Inheritance and Polymorphism.
Class Inheritance Part II: Overriding and Polymorphism Corresponds with Chapter 10.
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
Chapter 7: Cloning and RTTI
Inheritance and Polymorphism
CSE 413, Autumn 2002 Programming Languages
Presentation on Object Oriented programming Topic
Chapter 9 Inheritance and Polymorphism
Java Programming Language
Advanced Inheritance Concepts
Object-Oriented PHP (1)
Lecture 10 Concepts of Programming Languages
Presentation transcript:

Using Java™ Technology Reflection to Improve Design Michael T. Portwood, MS Exuberance, LLC

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 java.lang.Package 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 Determine if a class or interface 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 Find a specific method 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 Determine fields 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”

Question and Answer

Additional Information World Wide Web site www.exuberance4me.com Presentation Presentation notes Example applications E-mail contact portwood@exuberance4me.com