Programming Language Concepts: Lecture 9

Similar documents
Programming Language Concepts: Lecture 10

Programming Language Concepts: Lecture 6

Programming Language Concepts: Lecture 8

Chair of Software Engineering. Java and C# in depth. Carlo A. Furia, Marco Piccioni, Bertrand Meyer. Java: reflection

CSCE 314 TAMU Fall CSCE 314: Programming Languages Dr. Flemming Andersen. Java Reflection

Material Java type system Reflection

Lecture 9 : Basics of Reflection in Java

CSCE 314 Programming Languages

Programming Language Concepts: Lecture 7

Programming Language Concepts: Lecture 2

Concepts of Object-Oriented Programming Peter Müller

Reflection. Computer Science and Engineering College of Engineering The Ohio State University. Lecture 28

Introduction to Reflection

Programming Language Concepts: Lecture 2

Programming Language Concepts: Lecture 1

EPITA Première Année Cycle Ingénieur. Atelier Java - J3

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance

Programming Language Concepts: Lecture 11

EPITA Première Année Cycle Ingénieur. Atelier Java - J3

Java Threads. COMP 585 Noteset #2 1

JAVA. Reflection API. Java, summer semester

INHERITANCE. Spring 2019

M257 Past Paper Oct 2007 Attempted Solution

EPITA Première Année Cycle Ingénieur. Atelier Java - J3

Inheritance. Lecture 11 COP 3252 Summer May 25, 2017

Programming Language Concepts: Lecture 7

Java Magistère BFA

COMP 250. Lecture 32. polymorphism. Nov. 25, 2016

Computation Abstractions. Processes vs. Threads. So, What Is a Thread? CMSC 433 Programming Language Technologies and Paradigms Spring 2007

About This Lecture. Data Abstraction - Interfaces and Implementations. Outline. Object Concepts. Object Class, Protocol and State.

Graphical User Interfaces (GUIs)

CMSC131. Inheritance. Object. When we talked about Object, I mentioned that all Java classes are "built" on top of that.

Final Exam CS 251, Intermediate Programming December 13, 2017

Class 16: The Swing Event Model

CS180 Recitation. More about Objects and Methods

Object Oriented Programming: In this course we began an introduction to programming from an object-oriented approach.

Lecture 36: Cloning. Last time: Today: 1. Object 2. Polymorphism and abstract methods 3. Upcasting / downcasting

Self-test Java Programming

CS558 Programming Languages

CS/ENGRD 2110 SPRING Lecture 7: Interfaces and Abstract Classes

Abstract Classes and Interfaces

CS/ENGRD 2110 FALL Lecture 7: Interfaces and Abstract Classes

9/17/2018 Programming Data Structures. Encapsulation and Inheritance

Java Reflection. adapted from original slides by Tim Lethbridge University of Ottawa. Examining Classes. What is Reflection?

Some @SuppressWarnings

Week 7. Statically-typed OO languages: C++ Closer look at subtyping

Inheritance. The Java Platform Class Hierarchy

EMBEDDED SYSTEMS PROGRAMMING More About Languages

Polymorphism. return a.doublevalue() + b.doublevalue();

type conversion polymorphism (intro only) Class class

Overview. ITI Introduction to Computing II. Interface 1. Problem 1. Problem 1: Array sorting. Problem 1: Array sorting. Problem 1: Array sorting

Introduction to Inheritance

CS 61B Data Structures and Programming Methodology. July 3, 2008 David Sun

CS/ENGRD 2110 FALL Lecture 6: Consequence of type, casting; function equals

Block I Unit 2. Basic Constructs in Java. AOU Beirut Computer Science M301 Block I, unit 2 1

UMBC CMSC 331 Final Exam

CS-140 Fall 2017 Test 2 Version A Nov. 29, 2017

CS 2112 Lecture 20 Synchronization 5 April 2012 Lecturer: Andrew Myers

CS-202 Introduction to Object Oriented Programming

COE318 Lecture Notes Week 10 (Nov 7, 2011)

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring

CS/ENGRD 2110 FALL Lecture 6: Consequence of type, casting; function equals

Programming Languages and Techniques (CIS120)

MIT AITI Swing Event Model Lecture 17

CS558 Programming Languages

CMSC 132: Object-Oriented Programming II

EPITA Première Année Cycle Ingénieur. Atelier Java - J3

Advanced Programming - JAVA Lecture 4 OOP Concepts in JAVA PART II

DHANALAKSHMI SRINIVASAN COLLEGE OF ENGINEERING AND TECHNOLOGY ACADEMIC YEAR (ODD SEM)

Creating an Immutable Class. Based on slides by Prof. Burton Ma

CMSC 433 Programming Language Technologies and Paradigms. Spring 2013

Equality for Abstract Data Types

Chapter 11 Inheritance and Polymorphism. Motivations. Suppose you will define classes to model circles,

Super-Classes and sub-classes

CPS221 Lecture: Threads

Programming Languages and Techniques (CIS120)

Solution register itself

Object Oriented Programming

Lecture 19 GUI Events

Introduction to Programming Using Java (98-388)

Announcement. Agenda 7/31/2008. Polymorphism, Dynamic Binding and Interface. The class will continue on Tuesday, 12 th August

RAIK 183H Examination 2 Solution. November 10, 2014

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

Chapter 5: Enhancing Classes

Modern Programming Languages. Lecture Java Programming Language. An Introduction

ITI Introduction to Computing II

Programming Language Concepts: Lecture 5


CSE 331 Software Design & Implementation

Inheritance and Polymorphism

BFlat. Classes. A list of features: - Classes. - Static Types and Type Checking. - Static Scoping. - Metaclasses

References. Chapter 5: Enhancing Classes. Enhancing Classes. The null Reference. Java Software Solutions for AP* Computer Science A 2nd Edition

3 ADT Implementation in Java

Announcements/Follow-ups

Background. Reflection. The Class Class. How Objects Work

Introflection. Dave Landers BEA Systems, Inc.

Lecture 18 CSE11 Fall 2013 Inheritance

CSE 341, Autumn 2015, Ruby Introduction Summary

COE318 Lecture Notes Week 8 (Oct 24, 2011)

ITEC1620 Object-Based Programming. Lecture 13

Transcription:

Programming Language Concepts: Lecture 9 Madhavan Mukund Chennai Mathematical Institute madhavan@cmi.ac.in PLC 2011, Lecture 9, 10 February 2011

The event queue OS passes on low-level events to run-time support for event-driven components Run-time support generates high level events from low level events Events are stored in an event queue Can optimize e.g., combine consecutive mouse movements All events, low and high level, go into the queue Application may have a need to capture low level events as well May want to capture the mouse in an application In a line drawing program, after selecting the first point, must select the target point All other mouse events are captured and consumed Low level events have listener interfaces, like high level events

Manipulating the event queue Normally, a Java Swing program interacts with the queue implicitly Identify and associate listeners to events When an event reaches the head of the event queue, it is despatched to all listed listeners If there are no listeners, the event is discarded Can also explicitly manipulate event queue in Java Accessing the queue EventQueue evtq = Toolkit.getDefaultToolkit().getSystemEventQueue(); Consuming an event from the queue AWTEvent evt = eq.getnextevent(); Adding an event to the queue evtq.postevent(new ActionEvent(..));

Adding customized events Recall the timer example Suppose we want Timer to generate an event when its countdown expires Java events extend class AWTEvent Each event is identified by a unique numeric id class TimerEvent extends AWTEvent{ public static final int TIMER_EVENT = AWTEvent.RESERVED_ID_MAX + 5555; public TimerEvent(Timer t) { super(t, TIMER_EVENT); Constructor sets source of event and its type (numeric id)

Adding customized events An interface defining a listener for TimerEvents interface TimerListener extends EventListener{ public void timeelapsed(timerevent evt); and a class implementing the interface class MyClass implements TimerListener{ public void timeelapsed(timerevent evt){

Adding customized events Generate TimerEvents by manipulating event queue class Timer extends Component implements Runnable{ // Runnable is to ensure that Timer can run concurrently private static EventQueue evtq = Toolkit.getDefaultToolkit().getSystemEventQueue(); // There is only one copy of the EventQueue, shared by all Ti public Timer(){ public void f(){ // Generate a TimerEvent when done TimerEvent te = new TimerEvent(this); evtq.postevent(te);

Adding customized events Each Timer must keep track of its listeners Recall addlistener for JButton class Timer extends Component implements Runnable{ private TimerListener listener; public addlistener(timerlistener t){ listener = t;

Adding customized events Typical code that uses the timer Timer t = new Timer(); MyClass m = new MyClass(..); t.addlistener(m); t.start(); After t.start() completes, how does it know what to do to notify m?

Adding customized events It does not know! We have to tell it what to do AWT promises that a fixed function processevent will be called within an object whenever it generates an AWTEvent Add the following to Timer class Timer extends Component implements Runnable{ public void processevent(awtevent evt) { if (evt instanceof TimerEvent) { if (listener!= null) listener.timeelapsed((timerevent)evt); else super.processevent(evt);

Adding customized events Putting it all together When Timer t generates TimerEvent e, e is added to the system s event queue When event e comes up for processing at the head of the queue, AWT calls the (fixed) method processevent(e) within t In Timer, explicit code in processevent calls any listener associated with t To support multicasting, allow Timer to store an array of listeners and notify each in turn.

== vs equals I had claimed that == is always mapped to the equals(object) method defined in Object s == t is same as s.equals(t)

== vs equals I had claimed that == is always mapped to the equals(object) method defined in Object s == t is same as s.equals(t) This is not correct, apparently

== vs equals I had claimed that == is always mapped to the equals(object) method defined in Object s == t is same as s.equals(t) This is not correct, apparently == is always reference equality s == t returns true only if s and t refer to the same object

== vs equals I had claimed that == is always mapped to the equals(object) method defined in Object s == t is same as s.equals(t) This is not correct, apparently == is always reference equality s == t returns true only if s and t refer to the same object Predefined equals(object) in class Object has the same interpretation So, by default, s == t is same as s.equals(t)

== vs equals I had claimed that == is always mapped to the equals(object) method defined in Object s == t is same as s.equals(t) This is not correct, apparently == is always reference equality s == t returns true only if s and t refer to the same object Predefined equals(object) in class Object has the same interpretation So, by default, s == t is same as s.equals(t) However, if we redefine equals(object) in a class, == remains reference equality Equivalent of s is t in Python

Reflection Wikipedia says Reflection is the process by which a computer program can observe and modify its own structure and behaviour. Two components involved in reflection Introspection A program can observe, and therefore reason about its own state. Intercession A program can modify its execution state or alter its own interpretation or meaning.

Reflection in Java Simple example of introspection Employee e = new Manager(); if (e instanceof Manager){ What if we don t know the type that we want to check in advance? Suppose we want to write a function to check if two different objects are both instances of the same class? public static boolean classequal(object o1, Object o2){ // return true iff o1 and o2 point to objects of same type

Reflection in Java public static boolean classequal(object o1, Object o2){ Can t use instanceof Will have to check across all defined classes This is not even a fixed set! Can t use generic type variables The following code is syntactically disallowed if (o1 instance of T) {

Introspection in Java Can extract the class of an object using getclass() Import package java.lang.reflect import java.lang.reflect.*; class MyReflectionClass{ public static boolean classequal(object o1, Object o2){ return (o1.getclass() == o2.getclass()); What does getclass() return? An object of type Class that encodes class information

The class Class A version of classequal that explicitly uses this fact import java.lang.reflect.*; class MyReflectionClass{ public static boolean classequal(object o1, Object o2){ Class c1, c2; c1 = o1.getclass(); c2 = o2.getclass(); return (c1 == c2); For each currently loaded class C, Java creates an object of type Class with information about C Encoding execution state as data reification Representing an abstract idea in a concrete form

Using the Class object Can create new instances of a class at runtime Class c = obj.getclass(); Object o = c.newinstance(); // Create a new object of same type as obj Can also get hold of the class object using the name of the class String s = "Manager". Class c = Class.forName(s); Object o = c.newinstance();, or, more compactly Object o = Class.forName("Manager").newInstance();

The class Class From the Class object for class C, we can extract details about constructors, methods and fields of C Constructors, methods and fields themselves have structure Constructors: arguments Methods : arguments and return type All three: modifiers static, private etc Additional classes Constructor, Method, Field Use getconstructors(), getmethods() and getfields() to obtain constructors, methods and fields of C in an array.

The class Class Extracting information about constructors, methods and fields Class c = obj.getclass(); Constructor[] constructors = c.getconstructors(); Method[] methods = c.getmethods(); Field[] fields = c.getfields(); Constructor, Method, Field in turn have functions to get further details

The class Class Example: Get the list of parameters for each constructor Class c = obj.getclass(); Constructor[] constructors = c.getconstructors(); for (int i = 0; i < constructors.length; i++){ Class params[] = constructors[i].getparametertypes();.. Each parameter list is a list of types Return value is an array of type Class[]

The class Class We can also invoke methods and examine/set values of fields. Class c = obj.getclass();.. Method[] methods = c.getmethods(); Object[] args = { // construct an array of arguments methods[3].invoke(obj,args); // invoke methods[3] on obj with arguments args Field[] fields = c.getfields(); Object o = fields[2].get(obj); // get the value of fields[2] from obj fields[3].set(obj,value); // set the value of fields[3] in obj to value

Reflection and security Can we extract information about private methods, fields,? getconstructors(), only return publicly defined values Separate functions to also include private components getdeclaredconstructors() getdeclaredmethods() getdeclaredfields() Should this be allowed to all programs? Security issue! Access to private components may be restricted

Using reflection BlueJ, a programming environment to learn Java Can define and compile Java classes For compiled code, create object, invoke methods, examine state Uses reflective capabilities of Java BlueJ need not internally maintain debugging information about each class Look up http://www.bluej.org

Limitations of Java reflection Cannot create or modify classes at run time The following is not possible Class c = new Class(.); Note that BlueJ must invoke Java compiler before you can use a new class Languages such as Smalltalk allow redefining methods at run time Also Python!