CSE 331 Reflection slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia http://www.cs.washington.edu/331/

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.
Sadegh Aliakbary Sharif University of Technology Spring 2011.
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.
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Advanced Java Course Reflection. Reflection API What if you want to access information not just about the Object, but about that Object’s Class? What.
JVM-1 Java Virtual Machine Reading Assignment: Chapter 1: All Chapter 3: Sections.
C#.NET C# language. C# A modern, general-purpose object-oriented language Part of the.NET family of languages ECMA standard Based on C and C++
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 Classes, Encapsulation, Methods and Constructors Class definitions Scope of Data –Instance data –Local data The this Reference Encapsulation and Java.
1 Generics and Using a Collection Generics / Parameterized Classes Using a Collection Customizing a Collection using Inheritance Inner Classes Use of Exceptions.
1 Java object model Part 3: Serialization & Reflection.
Reflections on Reflection Objects from the inside out...
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.
Programming Languages and Paradigms Object-Oriented Programming.
1 Inheritance and Polymorphism Chapter 9. 2 Polymorphism, Dynamic Binding and Generic Programming public class Test { public static void main(String[]
Advanced Java Programming Lecture 5 Reflection dr hab. Szymon Grabowski dr inż. Wojciech Bieniecki
Topic 3 The Stack ADT.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
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.
The Reflection Lucielle Mendez Antonio Bologna.
Features of Object Oriented Programming Lec.4. ABSTRACTION AND ENCAPSULATION Computer programs can be very complex, perhaps the most complicated artifact.
1 Generics and Using a Collection Generics / Parameterized Classes Using a Collection Customizing a Collection using Inheritance Inner Classes Use of Exceptions.
An Object-Oriented Approach to Programming Logic and Design Chapter 3 Using Methods and Parameters.
© Keren Kalif Advanced Java Topics Written by Keren Kalif, Edited by Liron Blecher.
10-Nov-15 Java Object Oriented Programming What is it?
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
CSE 143 Lecture 24 Advanced collection classes (ADTs; abstract classes; inner classes; generics; iterators) read 11.1, 9.6, , slides.
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
AP Computer Science edition Review 1 ArrayListsWhile loopsString MethodsMethodsErrors
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.
CS305j Introduction to Computing Classes II 1 Topic 24 Classes Part II "Object-oriented programming as it emerged in Simula 67 allows software structure.
1 CSE 331 Generics (Parametric Polymorphism) slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia
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,
CSCE 314 Programming Languages Reflection Dr. Hyunyoung Lee 1.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Inheritance and Class Hierarchies Chapter 3. Chapter Objectives  To understand inheritance and how it facilitates code reuse  To understand how Java.
Topic 8Classes, Objects and Methods 1 Topic 8 l Class and Method Definitions l Information Hiding and Encapsulation l Objects and Reference Classes, Objects,
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
Inheritance ndex.html ndex.htmland “Java.
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.”
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
Reflection Mehdi Einali Advanced Programming in Java 1.
Reference Types CSE301 University of Sunderland Harry R Erwin, PhD.
1 CSE 331 Memento Pattern and Serialization slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia
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 7: Cloning and RTTI
Chapter 5: Enhancing Classes
NESTED CLASSES REFLECTION PROXIES.
Java Programming Course
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 Behnam Hatami Fall 2017.
Advanced Programming in Java
Java Programming Language
The Building Blocks Classes: Java class library, over 1,800 classes:
Advanced Programming in Java
CSE 331 Memento Pattern slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia
Some Examples Reflection is used for many things:
Reflection in Java By: Zachary Cava.
Software Specifications
Presentation transcript:

CSE 331 Reflection slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia http://www.cs.washington.edu/331/

Reflection reflection: A process by which a program can examine its own types and structure at runtime. sometimes called run-time type inference (RTTI) import java.lang.reflect.*; Using reflection, you can: Convert strings and others into classes and objects at runtime. Ask detailed questions in code about the abilities of a type. Dynamically compile, load, and add classes to a running program. Pass function pointers (via Method objects) Reflection is used internally by many Java technologies including IDEs/compilers, debuggers, serialization, Java Beans, RMI, ...

The Class class An object of type Class represents information about a Java class. Its fields, methods, constructors, superclass, interfaces, etc. A gateway to the rest of Java's reflection system. Object Class get/set compiled class file Field invoke Method Constructor Member

Accessing a Class object Ways to get a Class object: If you have an object: Every object has a getClass method to return the Class object that corresponds to that object's type. Class<Point> pointClass = p.getClass(); If you don't have an object, but know the class's name at compile time: Every class has a static field named class storing its Class object. Class<Point> pointClass = Point.class; If you don't know the type until given its name as a string at runtime: The static method Class.forName(String) will return the Class object for a given type; pass it a full class name. Class<?> clazz = Class.forName("java.awt.Point");

Class class methods getConstructor(params) getConstructors() description getConstructor(params) getConstructors() objects representing this class's constructors getField(name) getFields() objects representing this class's fields getInterfaces() interfaces implemented by this class getMethod(name, params) getMethods() objects representing this class's methods getModifiers() whether the class is public, static, etc. getName() full name of this class, as a string getPackage() object representing this class's package newInstance() constructs a new object of this type (if the type has a parameterless constructor) toString() string matching the class's header

Class class methods 2 getAnnotation(class) getAnnotations() description getAnnotation(class) getAnnotations() information about annotations on the class getResource(name) getResourceAsStream(name) resource-loading features getSuperclass() a Class object for this type's superclass getSimpleName() class name without package name getTypeParameters() all generic type params in this class isAnnotation() isAnnotationPresent(type) information about annotation types isAnonymousClass() isArray(), isEnum() isInterface(),isPrimitive() testing whether the class fits into one of the given categories of types isAssignableFrom(class) whether this class is the same as or a supertype of the given class parameter getDeclaredFields(), ... fields/methods/etc. declared in this file

Reflection example Print all the methods and fields in the Point class: for (Method method : Point.class.getMethods()) { System.out.println("a method: " + method); } for (Field field : Point.class.getFields()) { System.out.println("a field: " + field);

Primitives and arrays Primitive types and void are represented by Class constants: Not to be confused with Integer.class, Double.class, etc., which represent the wrapper classes Integer, Double, etc. Array classes are manipulated in reflection by static methods in the Array class (not to be confused with java.util.Arrays). constant alternate form primitive Integer.TYPE int.class int Double.TYPE double.class double Character.TYPE char.class char Boolean.TYPE boolean.class boolean Void.TYPE void.class void ...

Generic Class class As of Java 1.5, the Class class is generic: Class<T> This is so that known types can be instantiated without casting. Class<Point> clazz = java.awt.Point.class; Point p = clazz.newInstance(); // no cast For unknown types or Class.forName calls, you get a Class<?> and must still cast when creating instances. Class<?> clazz = Class.forName("java.awt.Point"); Point p = (Point) clazz.newInstance(); // must cast

Method class methods getDeclaringClass() description getDeclaringClass() the class that declares this method getExceptionTypes() any exceptions the method may throw getModifiers() whether the method is public, static, etc. getName() method's name as a string getParameterTypes() info about the method's parameters getReturnType() info about the method's return type invoke(obj, params) calls this method on given object (null if static), passing given parameter values toString() string matching the method's header

Reflection example 1 Calling various String methods in an Interactions pane: // "abcdefg".length() => 7 > Method lengthMethod = String.class.getMethod("length"); > lengthMethod.invoke("abcdefg") 7 // "abcdefg".substring(2, 5) => "cde" > Method substr = String.class.getMethod("substring", Integer.TYPE, Integer.TYPE); > substr.invoke("abcdefg", 2, 5) "cde"

Reflection example 2 Calling translate on a Point object: // get the Point class object; create two new Point()s Class<Point> clazz = Point.class; Point p = clazz.newInstance(); Point p2 = clazz.newInstance(); // get the method Point.translate(int, int) Method trans = clazz.getMethod("translate", Integer.TYPE, Integer.TYPE); // call p.translate(4, -7); trans.invoke(p, 4, -7); // call p.getX() Method getX = clazz.getMethod("getX"); double x = (Double) getX.invoke(p); // 4.0

Modifier static methods if (Modifier.isPublic(clazz.getModifiers()) { ... static method description isAbstract(mod) is it declared abstract? isFinal(mod) is it declared final? isInterface(mod) is this type an interface? isPrivate(mod) is it private? isProtected(mod) is it protected? isPublic(mod) is it public? isStatic(mod) is it static? isSynchronized(mod) does it use the synchronized keyword? isTransient(mod) is the field transient? isVolatile(mod) is the field volatile? toString(mod) string representation of the modifiers such as "public static transient"

Field class methods get(obj) description get(obj) value of this field within the given object getBoolean(obj),getByte(obj) getChar(obj),getDouble(obj) getFloat(obj),getInt(obj) getLong(obj),getShort(obj) versions of get that return more specific types of data getDeclaringClass() the class that declares this field getModifiers() whether the field is private, static, etc. getName() field's name as a string getType() a Class representing this field's type set(obj, value) sets the given object's value for this field setBoolean(obj, value), setByte(obj, value), ... versions of set that use more specific types of data toString() string matching the field's declaration

Constructor methods getDeclaringClass() description getDeclaringClass() the class that declares this constructor getExceptionTypes() any exceptions the constructor may throw getModifiers() whether the constructor is public, etc. getName() constructor's name (same as class name) getParameterTypes() info about the constructor's parameters getReturnType() info about the method's return type newInstance(params) calls this constructor, passing the given parameter values; returns object created toString() string matching the constructor's header

Array class methods The Class object for array types has a useful method: static method description get(array, index) value of element at given index of array getBoolean(array, index), getChar(array, index), getDouble(array, index), getInt(array, index), getLong(array, index), ... versions of get that return more specific types of data getLength(array) length of given array object newInstance(type, length) construct new array with given attributes set(array, index, value) sets value at given index of given array setBoolean(array,index,value), setChar(array,index,value),... versions of set that use more specific types of data static method description getComponentType() a Class object for the type of elements

Invocation exceptions If something goes wrong during reflection, you get exceptions. Almost all reflection calls must be wrapped in try/catch or throw. Example: ClassNotFoundException, NoSuchMethodError When you access a private field, you get an IllegalAccessException. Else reflection would break encapsulation. When you call a method via reflection and it crashes, you will receive an InvocationTargetException. Inside this is a nested exception containing the actual exception thrown by the crashing code. You can examine the nested exception by calling getCause() on the invocation target exception.

Misuse of reflection Some programmers who learn reflection become overly enamored with it and use it in places where it wasn't intended. Example: Passing a Method as a way to get a "function pointer." Example: Checking the Class of values as a way of testing types. Reflection code is usually bulky, ugly, brittle, and hard to maintain. Reflection is for certain specific situations only. When you don't know what type to use until runtime. When you want to be able to dynamically create or load classes while a program is running (example: CSE 14x Practice-It tool). When you want to check information about a particular type. When you want to write testing/grading libraries like JUnit.

Reflection examples The CSE 142 Critters simulator uses reflection to load all of the student's critter animal classes into the system. Uses reflection to look for all classes with a superclass of Critter, constructs new instances of them, and adds them to the simulator. The CSE 14x Practice-It! tool uses reflection to dynamically compile, load, run, and test program code submitted by students. The student's code is injected into a randomly named new class. The class is written to disk, compiled, and loaded into the VM. By reflection, the methods/code in the class are executed and tested. Test results are gathered and shown to the student.

Reflection exercise Write a JUnit test to help grade the internal correctness of a student's submitted program for a hypothetical assignment. Make the tests fail if the class under test has any of the following: more than 4 fields any non-private fields any fields of type ArrayList fewer than two private helper methods any method that has a throws clause any method that returns an int missing a zero-argument constructor