03G-1 Reflection In Java “Reflection is the ability of a program to manipulate as data something representing the state of the program during its own execution.”

Slides:



Advertisements
Similar presentations
Reflection Reflection is the ability of a program to examine and modify the structure and behavior of an object at runtime.
Advertisements

Java Virtual Machine (JVM). Lecture Objectives Learn about the Java Virtual Machine (JVM) Understand the functionalities of the class loader subsystem.
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.
Slide 11.1 Advanced Programming 2004, based on LY Stefanus’s Slides Reflection Reflection is the ability for a class or object to examine itself. Java.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Inheritance and Polymorphism.
JVM-1 Java Virtual Machine Reading Assignment: Chapter 1: All Chapter 3: Sections.
Type-safe Implementation of Java ™ Reflection Nadeem Abdul Hamid February 27, 2001 Yale University Advisor: Prof. Zhong Shao (Work in progress)
1 Java Reflection. 2 Java looking at Java l One of the unusual capabilities of Java is that a program can examine itself »You can determine the class.
JVM-1 Java Virtual Machine Reading Assignment: Chapter 1: All Chapter 3: Sections.
Java Virtual Machine (JVM). Lecture Objectives Learn about the Java Virtual Machine (JVM) Understand the functionalities of the class loader subsystem.
1 Java Reflection. 2 Java looking at Java l One of the unusual capabilities of Java is that a program can examine itself »You can determine the class.
1 Chapter 6 Inheritance, Interfaces, and Abstract Classes.
03G-1 Reflection In Java For every loaded class, the Java Runtime Environment (JRE) maintains an associated Class object The Class object “ reflects ”
1 Inheritance and Polymorphism. 2 Motivations Suppose you will define classes to model circles, rectangles, and triangles. These classes have many common.
1 Java object model Part 3: Serialization & Reflection.
1 Java reflections API Lecture 1. 2 Assignments Java 1.4 or Java 1.5? Both are ok, but the assignments are written for Java 1.4, and specific Java 1.5.
Unit 061 Java Virtual Machine (JVM) What is Java Virtual Machine? The Class Loader Subsystem Linking oVerification oPreparation oResolution Class Initialization.
13-Jul-15 Reflection. 2 Java looking at Java One of the unusual capabilities of Java is that a program can examine itself You can determine the class.
Reflection API Faculty of Information Technologies Industrial University of Ho Chi Minh City Java Programming Course 1.
1 Inheritance and Polymorphism Chapter 9. 2 Polymorphism, Dynamic Binding and Generic Programming public class Test { public static void main(String[]
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 11 Inheritance and Polymorphism.
Advanced Java Programming Lecture 5 Reflection dr hab. Szymon Grabowski dr inż. Wojciech Bieniecki
CISC6795: Spring Object-Oriented Programming: Polymorphism.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved COS240 O-O Languages AUBG,
SEG4110 – Advanced Software Design and Reengineering TOPIC H Java Reflection.
Java Reflection. Compile-Time vs Run-Time Some data you know at compile time: int area = radius*radius*3.14; The “3.14” is set – known at compile time.
Object Oriented Programming in Java Lecture 13. Java Reflection Reflection is a feature unique to Java that allows an executing program to examine or.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
The Reflection Lucielle Mendez Antonio Bologna.
Course contents Basic concepts –What is software architecture ? Fundamental architectural styles –Pipes and filters –Layers –Blackboard –Event-driven Architectural.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 11 Inheritance and Polymorphism.
Reflection in Java Bibliografie: Sun: The Java Tutorials – The Reflection API Java 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…..
1 The finalize, clone, and getClass Methods  The finalize method is invoked by the garbage collector on an object when the object becomes garbage.  The.
CS884 (Prasad)java11Extn1 Java 1.1 Extensions Nested classes static public/protected/private.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 9 Inheritance and.
Programming With Java ICS201 University Of Ha’il1 Chapter 7 Inheritance.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 10 Inheritance and.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
CSCE 314 Programming Languages Reflection Dr. Hyunyoung Lee 1.
Reflection Bibliografie: Sun: The Java Tutorials – The Reflection API IBM developerWorks:
COM S 228 Introduction to Data Structures Instructor: Ying Cai Department of Computer Science Iowa State University Office: Atanasoff.
Chapter 11: Advanced Inheritance Concepts. Objectives Create and use abstract classes Use dynamic method binding Create arrays of subclass objects Use.
1 Chapter 4 Inheritance and Polymorphism. 2 Objectives u To develop a subclass from a superclass through inheritance. u To invoke the superclass’s constructors.
CSE 331 Reflection slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia
Inheritance ndex.html ndex.htmland “Java.
CS 112 Programming 2 Lecture 06 Inheritance & Polymorphism (1)
1 Chapter 2 Inheritance and Polymorphism. 2 Objectives u To develop a subclass from a superclass through inheritance. u To invoke the superclass’s constructors.
Exam 2 EXAM 2 Thursday!!! 25% of Final Grade Know: loops, switch/case Files Input failure (e.g. scan.hasNextInt())
Reflection Mehdi Einali Advanced Programming in Java 1.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 10 Inheritance and Polymorphism.
Chapter 7: Cloning and RTTI
NESTED CLASSES REFLECTION PROXIES.
Java Programming Course
Chapter 11 Inheritance and Polymorphism
Java as a Dynamic Language
Inheritance and Polymorphism
CSE 413, Autumn 2002 Programming Languages
Presentation on Object Oriented programming Topic
EE 422C Java Reflection re·flec·tion rəˈflekSH(ə)n/ noun
Методика наставе рачунарства
Advanced Programming in Java
Java Programming Language
Type Safety, Generics, Lambdas, Class Object
What is Reflection? Some Definitions….
What is Reflection? Some Definitions….
CSCE 314: Programming Languages Dr. Dylan Shell
Reflection in Java By: Zachary Cava.
Presentation transcript:

03G-1 Reflection In Java “Reflection is the ability of a program to manipulate as data something representing the state of the program during its own execution.” [Demers and Malenfant] For every loaded class, the JVM maintains an associated Class object The Class object “ reflects ” the class it represents The primitive Java types are also represented as Class objects Instances of the class Class store information about classes Class name Inheritance Interfaces implemented Methods, members, etc. Can look up instances: By name or From an object

03G-2 Accessing the Class object To get the Class object for an object mystery: Class c = mystery.getClass(); Or, using the class type: Class c = mysteryClass.class; Or, using the class name: Class c = Class.forName(“mysteryClass”); Getting the superclass of MysteryClass: Class s = c.getSuperclass(); Getting the class name: String s = c.getName(); Discovering the interfaces implemented by a class: Class[] interfaces = c.getInterfaces(); Discovering the fields of a class: Field[] fields = c.getFields(); Discovering the methods of a class: Method[] methods = c.getMethods();

03G-3 Example – exploring a type public static void showType(String className) throws ClassNotFoundException { Class thisClass = Class.forName(className); String flavor = thisClass.isInterface() ? "interface" : "class"; System.out.println(flavor + " " + className); Class parent = thisClass.getSuperclass(); if (parent != null) { System.out.println("extends " + parent.getName()); } Class[] interfaces = thisClass.getInterfaces(); for (int i=0; i<interfaces.length; ++i) { System.out.println("implements "+ interfaces[i].getName()); }

03G-4 The Output class java.lang.Object class java.util.HashMap extends java.util.AbstractMap implements java.util.Map implements java.lang.Cloneable implements java.io.Serializable class Point extends java.lang.Object

03G-5 Displaying Methods static void showMethods(Object o) { Class c = o.getClass(); Method[] theMethods = c.getMethods(); for (int i = 0; i < theMethods.length; i++) { String methodString = theMethods[i].getName(); System.out.println("Name: " + methodString); System.out.println(" Return Type: " + theMethods[i].getReturnType().getName()); Class[] parameterTypes = theMethods[i].getParameterTypes(); System.out.print(" Parameter Types:"); for (int k = 0; k < parameterTypes.length; k ++) { System.out.print(" " + parameterTypes[k].getName()); } System.out.println(); }

03G-6Output Output for a call of the form: Polygon p = new Polygon(); showMethods(p);. Name: equals Return Type: boolean Parameter Types: java.lang.Object Name: getClass Return Type: java.lang.Class Parameter Types: Name: intersects Return Type: boolean Parameter Types: double double double double

03G-7 Main Java reflection Classes u Class ( java.lang.Class ) l Instances of the class Class represent classes and interfaces in a running Java application, every object is represented by a Class object. u Package java.lang.reflect: l Member ( java.lang.reflect.Member ) An Interface that reflects identifying information about a single member (a field or a method) or a constructor. l Method ( java.lang.reflect.Method ) Implements Member Interface provides information about, and access to, a single method on a class or interface. Represents instance methods and class methods ( static ) l Field Implements Member Interface provides information about, and dynamic access to, a single field ( also for static fields ) Provides access and modification ( set, get ) methods.

03G-8 Main Java reflection Classes l Constructor provides information about, and access to, a single constructor for a class. l Package Package objects contain version information about the implementation and specification of a Java package l Modifier provides static methods and constants to decode class and member access modifiers. The sets of modifiers are represented as integers with distinct bit positions representing different modifiers

03G-9 Reflection API Interface - example class Class{ static Class forName(String name); Object newInstance(); Field getField(String name); Method getMethod(String name, Class[] paramTypes); //other methods: getName(), getInterfaces(), // getSuperclass(), getModifiers(), // getFields(), getMethods(), … } class Field extends AccessibleObject { Object get(Object obj); void set(Object obj, Object val); //other methods: getType(), getDeclaringClass(),... }

03G-10 Exploring the Instantiation Hierarchy public static void traverse(Object o){ for (int n = 0; ; o = o.getClass()) { System.out.println("L"+ ++n + ": " + o + ".getClass() = " + o.getClass()); if (o == o.getClass()) break; } public static void main(String[] args){ traverse(new Integer(3)); } L1: 3.getClass() = class java.lang.Integer L2: class java.lang.Integer.getClass() = class java.lang.Class L3: class java.lang.Class.getClass() = class java.lang.Class

03G-11 Using Arrays u Reflection can be used to create and manipulate arrays whose size and component type are not known until runtime public static void testArray(){ Class cls = String.class; int i=10; Object arr = Array.newInstance(cls, i); Array.set(arr, 5, "this is a test"); String s = (String)Array.get(arr, 5); System.out.println(s); }

03G-12 A Java Reflection Example u Illustrates Four Issues: l Runtime type Information (RTTI) l Introspection l Invoking Method Objects l Dynamic Instantiation

03G-13 Back to our Employee Example … Employee number level print() MonthlyEmployee print() HourlyEmployee print() Only partial view of the classes … public final class MonthlyEmployee extends Employee { public void print() { System.out.println("I’m a Monthly Employee"); } public final class HourlyEmployee extends Employee { public void print() { System.out.println("I’m a Hourly Employee"); }

03G-14 Reflection and Dynamic Binding What is the output of the following test code: Employee e; e = new MonthlyEmployee(); Class c = e.getClass(); System.out.println("class of e = " + c.getName()); e = new HourlyEmployee(); c = e.getClass(); System.out.println("class of e = " + c.getName()); class of e = MonthlyEmployee class of e = HourlyEmployee

03G-15SuperClass What is the output of the following test code: c = c.getSuperclass(); System.out.println("base class of e = " + c.getName()); c = c.getSuperclass(); System.out.println("base of base class of e = " + c.getName()); base class of e = Employee base of base class of e = java.lang.Object

03G-16 Getting and setting fields u Non public fields are not printed! getDeclaredFields returns all fields declared by the class, but excludes inherited ones Field fields[] = c.getFields(); for(int i = 0; i < fields.length; i++) { System.out.print(fields[i].getName() + "= "); System.out.println(fields[i].getInt(e)); } e is an instance of Employee or its subtype The output produced: number= 111 level= 12 Field f = c.getField("level"); f.setInt(e,f.getInt(e)+1);

03G-17 Examining Modifiers What is the output of the following test code: int m = c.getModifiers(); if (Modifier.isPublic(m)) System.out.println("public"); if (Modifier.isAbstract(m)) System.out.println("abstract"); if (Modifier.isFinal(m)) System.out.println("final"); public final

03G-18 Invoking Method Objects We can ask a method object to invoke the method it represents we must provide it with the implicit and explicit arguments Employee e = new HourlyEmployee(); Class c = e.getClass(); Method m = c.getMethod("print", null); m.invoke(e, null); the output produced: I’m a Hourly Employee

03G-19 Dynamic Instantiation The universal printer gets the employee type and invokes the print method. class UniversalPrinter { public void print(String empType) { Class c = Class.forName(empType); Employee emp = (Employee ) c.newInstance(); emp.print(); } - for calling other constructors (with arguments), use the Constructor class - Constructor c =... - Object newObject = c.newInstance( Object[] initArguments ) What is the output of the following code? UniversalPrinter p = new UniversalPrinter(); String empType; empType = "HourlyEmployee"; p.print(empType); empType = "MonthlyEmployee"; p.print(empType);

03G-20 Implementing Java Reflection u At runtime, JVM loads class files and creates objects representing the classes. l Object representing a class has a name (string field), list of fields (each of type Field), list of methods… class Field { String name; Class type; Class clazz; int offset; Object get(Object obj) { if (clazz.isInstance(obj)) { f = ((char*)obj) + offset; return (type.primitive = TRUE ? wrap(f) : (Object)f); } } } class Class { String name; Field[] fields; Method[] methods; boolean primitive; bool isInstance... Object newInstance.. }

03G-21 Reflection - What ’ s missing u Reflection is introspection only l Cant add / modify fields (structure), methods (behavior) u Implementation is not available l Program logic is not reflected u Major performance impact l Much slower then doing the same operations directly … u Complex code

03G-22 Java Serialization u the process of converting objects into a linear stream of bytes l Depends on reflection public class PersistentTime implements Serializable{ private Date time; public PersistentTime(){ time = Calendar.getInstance().getTime(); } public Date getTime(){return time;} } String filename = "time.ser"; PersistentTime time = new PersistentTime(); FileOutputStream fos = null; ObjectOutputStream out = null; fos = new FileOutputStream(filename); out = new ObjectOutputStream(fos); out.writeObject(time); out.close();