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.

Slides:



Advertisements
Similar presentations
Introduction to Java Reflection
Advertisements

The ArrayList Class and the enum Keyword
COSC 2006 Data Structures I Instructor: S. Xu URL:
Interfaces CSC 171 FALL 2004 LECTURE 14. Project 1 review public class Rational { private int numerator, denominator; public Rational(int numerator, int.
Exceptions Session 21. Memory Upload Creating Exceptions Using exceptions to control object creation and validation.
CSCI 160 Midterm Review Rasanjalee DM.
INHERITANCE BASICS Reusability is achieved by INHERITANCE
Problem Solving 5 Using Java API for Searching and Sorting Applications ICS-201 Introduction to Computing II Semester 071.
Reflection Reflection is the ability of a program to examine and modify the structure and behavior of an object at runtime.
Written by: Dr. JJ Shepherd
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.
Java Exceptions. Types of exceptions  Checked exceptions: A checked exception is an exception that is typically a user error or a problem that cannot.
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.
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.
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 Object Model Part 1. 2 Type Definition: set of values – a set of values and set of operations –a set of operations that can be applied to those.
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 Java object model Part 3: Serialization & Reflection.
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.
Java CourseWinter 2009/10. Introduction Object oriented, imperative programming language. Developed: Inspired by C++ programming language.
CIS3023: Programming Fundamentals for CIS Majors II Summer 2010 Ganesh Viswanathan Exception Handling in Java Course Lecture Slides 7 th July 2010 “ Admitting.
Principles of Computer Programming (using Java) Review Haidong Xue Summer 2011, at GSU.
Advanced Java Programming Lecture 5 Reflection dr hab. Szymon Grabowski dr inż. Wojciech Bieniecki
1 Review of Java Higher Level Language Concepts –Names and Reserved Words –Expressions and Precedence of Operators –Flow of Control – Selection –Flow of.
Type Safety and Enumerations. Type Checking and Type Errors  The type system defines data types and the operations on data types.  A type error occurs.
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.
Lecture objectives  Differences between Java and C#  Understand and use abstract classes  Casting in Java: why is it important?  Master exceptions.
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.
Java Quiz Bowl A fun review of the Java you should know from CMPT 201 If you don’t know the answers - this week is for you to study up!
Lecture # 8 Constructors Overloading. Topics We will discuss the following main topics: – Static Class Members – Overloaded Methods – Overloaded Constructors.
Arrays and ArrayLists in Java L. Kedigh. Array Characteristics List of values. A list of values where every member is of the same type. Each member in.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
CSC1401 Classes - 2. Learning Goals Computing concepts Adding a method To show the pictures in the slide show Creating accessors and modifiers That protect.
Lecture 101 CS110 Lecture 10 Thursday, February Announcements –hw4 due tonight –Exam next Tuesday (sample posted) Agenda –questions –what’s on.
CourseOutline Example & JavaBeans Lec Start with Example Displaying Course Outlines User will select either course “web design & development” or.
MIT AITI 2004 – Lecture 13 Abstract Classes and Interfaces.
CMSC 341 Java Packages, Classes, Variables, Expressions, Flow Control, and Exceptions.
Exceptions Chapter 16 This chapter explains: What as exception is Why they are useful Java exception facilities.
COP3502 Programming Fundamentals for CIS Majors 1 Instructor: Parisa Rashidi.
CreatingClasses-SlideShow-part31 Creating Classes part 3 Barb Ericson Georgia Institute of Technology Dec 2009.
C OMP 401 R EFLECTION AND A CTION O BJECTS Instructor: Prasun Dewan.
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
CSCE 314 Programming Languages Reflection Dr. Hyunyoung Lee 1.
CSE 331 Reflection slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia
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.”
OOP in Java : © W. Milner 2005 : Slide 1 Java and OOP Part 3 – Extending classes.
Topics Instance variables, set and get methods Encapsulation
Reflection Mehdi Einali Advanced Programming in Java 1.
Advanced Java class Nested Classes & Interfaces. Types of Nested Classes & Interfaces top-level nested –classes –interfaces inner classes –member –local.
COMP Inheritance and Polymorphism Yi Hong June 09, 2015.
Last Revision. Question1 Novice Java programmers often write code similar to, class C { public int x;... }... C[] a = new C[10]; for(int i = 0; i < a.length;
Garbage Collection It Is A Way To Destroy The Unused Objects. To do so, we were using free() function in C language and delete() in C++. But, in java it.
Object Oriented Programming Lecture 2: BallWorld.
Programming in Java Transitioning from Alice. Becomes not myFirstMethod but …. public static void main (String[] arg) { // code for testing classes goes.
N ESTED C LASSES -1. T YPES OF N ESTED C LASSES & I NTERFACES top-level nested classes interfaces inner classes member local named anonymous.
Object Oriented Programming. Constructors  Constructors are like special methods that are called implicitly as soon as an object is instantiated (i.e.
Chapter 7: Cloning and RTTI
Java Programming Course
Objects as a programming concept
CSE 413, Autumn 2002 Programming Languages
CSC 113 Tutorial QUIZ I.
Advanced Programming in Java
Classes Lecture 7 from Chapter /1/11.
Advanced Programming in Java
Some Examples Reflection is used for many things:
Barb Ericson Georgia Institute of Technology Oct 2005
Presentation transcript:

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 if you want to access a method, field, or constructor whose name you don’t know at compile time?

Example: WebCrawler timer To optimize your WebCrawler, first find out how long each big operation is taking. –Getting content from URLs –Parsing pages –Setting up Database Connection & Statement –Deleting from the Database –Inserting into the Database –Other?

How to time an operation? Without reflection: int startTime = System.currentTimeMillis(); doOperation(...); int endTime = System.currentTimeMillis(); int duration = endTime – startTime; Problem: Code is repeated every place you want to time an operation! Not clean at all...

A better way to time an operation Object timeMethod(String methodToCall, Class[] argTypes, Object[] args, String timeToUpdateField) {...} timeMethod(“methodName”, new Class[] {...}, new Object[] {...}, “timeStoringField”); No code repetition, less clutter!

Classes in the Reflection API Class Class Constructor Class Field Class Method

Getting an Object of type Class If you have an instance of the class: –Class classObject = instanceObject.getClass(); If you know the name of the class at compile time: –Class classObject = ClassName.class If you know the name of the class at run time: –Class.forName(“...”); If you want a primitive type class, and you know the name of the wrapper class at compile time; –Integer.TYPE, Long.TYPE, etc

some methods in the Class class getName() getSuperClass() getComponentType() – [null if !isArray()] isArray() isInterface() isPrimitive() isInstance(Object o) Object newInstance()

Getting Constructors/Methods/Fields ask the Class Object for them –classObject.getConstructors() –classObject.getConstructor( Class[] argTypes) –classObject.getDeclaredConstructors() –classObject.getDeclaredConstructors( Class[] argTypes) Methods and Fields have analogous getters in class Class. you can get an array of all the c/m/f in the class, or just one by name, and if you ask for “Declared” it gives you the non-public ones as well.

Objects of Type Method calling a method dynamically: –Object methodObject.invoke(Object o, Object[] args); getting info about it: –Class[] getParameterTypes() –Class getReturnType() –Class[] getExceptionTypes()

Objects of type Field Object fieldObject.get( Object o ); –also getInt(Object), getBoolean(Object), etc. void fieldObject.set( Object o, Object value ); –also setInt(Object o, int i), etc. Class fieldObject.getType() [compile time, of course] Fields of type int will have Integer.TYPE as the result of getType(), and it’s a Class Object.

Objects of type Constructor Object constructorObject.newInstance( Object[] args ) Class[] constructorObject.getExceptionTypes() Class[] constructorObject.getParameterTypes()

Member Interface Method, Field, and Constructor classes all extend the Member Interface Class getDeclaringClass() String getName() int getModifiers()

Modifier class (static methods) How do you know if something is static, final, etc.? int getModifiers() [from Member Interface] Modifer.isStatic(int) Modifer.isFinal(int) Modifier.isProtected(int) etc.

Array class (static methods) Object Array.get(Object arrayObject, int i); void Array.set(Object arrayObject, int index, Object value) int Array.getLength(Object arrayObject); Object newInstance(Class type, int length) Object newInstance(Class type, int[] dimensions)

Reflection Group Task #1 Fill in example from beginning of lecture: Object timeMethod(String methodToCall, Class[] argTypes, Object[] args, String timeToUpdateField) {... Please fill this in!... }

Solution to Reflection Group Task 1 Object timeMethod(String methodToCall, Class[] argTypes, Object[] args, String timeToUpdateField) throws NoSuchMethodException, NoSuchFieldException, InvocationTargetException, IllegalAccessException { Class c = this.getClass(); long startTime = System.currentTimeMillis(); Method m = c.getMethod(methodToCall, argTypes); Object returnValue = m.invoke(this, args); long endTime = System.currentTimeMillis(); Field f = c.getField(timeToUpdateField); f.setLong(this, f.getLong(this) + (endTime - startTime)); return returnValue; }

Reflection Group Task #2 Fill in the class definition to call all getX methods and print their values in the form: ClassName propertyName = value import java.lang.reflect.*; public class PropertyValueFinder { final String GET = "get"; public void printProperties(Object o) { /*fill this in*/ } private Property propertyGottenBy(Method method) { /*fill this in*/} private boolean isGetter(Method method) { /*fill this in*/ } public class Property { String name; Class type; Object value; public Property(String name, Class type) { this.name = name; this.type = type; } public void setValue(Object value) { this.value = value; } public String toString() { return type+" "+name+" = "+value; } }

Group Task #2 Solutions private boolean isGetter(Method m) { boolean nameOK = m.getName().startsWith(GET); boolean noArgs = m.getParameterTypes().length == 0; boolean nonVOID = m.getReturnType() != Void.TYPE; return nameOK && noArgs && nonVOID; } private Property propertyGottenBy(Method m) { if (!isGetter(m)) return null; Class propertyType = m.getReturnType(); String propertyName = m.getName().substring(GET.length()); return new Property(propertyName, propertyType); }

Group Task #2 Solutions public void printProperties(Object o) { Class oClass = o.getClass(); Method[] methods = oClass.getMethods(); for (int i = 0; i < methods.length; i++) { Method m = methods[i]; if (isGetter(m)) { try { Object value = m.invoke(o, new Object[0]); Property p = propertyGottenBy(m); p.setValue(value); System.out.println(p); } catch (IllegalAccessException e) { throw new RuntimeException(); //programmer error } catch (IllegalArgumentException e) { throw new RuntimeException(); //programmer error } catch (InvocationTargetException e) { throw new RuntimeException(); //programmer error }

Discussion Topic Restriction to Serializer project: I must promise that the Objects I test your code on will have a no-args constructor that: –sets the value of any final variables that are not set in the class definition –does not throw any exceptions. If you could add functionality to the Reflection API, how would you fix this without compromising the integrity of the keyword final? Work in teams, and then we’ll exchange ideas. Great, now go start a JSR (Java Specification Request)! –