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

Slides:



Advertisements
Similar presentations
Introduction to Java Reflection
Advertisements

Reflection & Generics in JDK1.5 / J.J. Hou / /
Continuation of chapter 6…. Nested while loop A while loop used within another while loop is called nested while loop. Q. An illustration to generate.
Clonazione La clonazione... Ovvero: come costruire una copia (probabilmente che ritorni true su equals?)
Architecture (simplified view) method object Reflection plane Object plane Class object Method object.
1 Streams and Input/Output Files Part 2. 2 Files and Exceptions When creating files and performing I/O operations on them, the systems generates errors.
Using Java™ Technology Reflection to Improve Design
8 March 2013Birkbeck College, U. London1 Introduction to Programming Lecturer: Steve Maybank Department of Computer Science and Information Systems
Recitation 4. 2-D arrays. Exceptions. Animal[] v= new Animal[3]; 2 declaration of array v v null Create array of 3 elements a6 Animal[] null Assign.
Introduction to Computer Science Robert Sedgewick and Kevin Wayne Recursive Factorial Demo pubic class Factorial {
Phil Campbell London South Bank University Java 1 First Steps.
Purpose : To convert this string to a new character array. Return Type : char[ ] Parameters : none Declaration : public char[ ] toCharArray() Returns.
SCJP 6.0 Lecturer Kuo-Yi Chen 151, 153, 154, 155, 156, 157
 Specifies a set of methods (i.e., method headings) that any class that implements that interface must have.  An interface is a type (but is not a class).
The Line Class Suppose you are involved in the development of a large mathematical application, and this application needs an object to represent a Line.
Exceptions Session 21. Memory Upload Creating Exceptions Using exceptions to control object creation and validation.
Topic 10 Java Memory Management. 1-2 Memory Allocation in Java When a program is being executed, separate areas of memory are allocated for each class.
CSCI 160 Midterm Review Rasanjalee DM.
Copyright 2010 by Pearson Education Building Java Programs Chapter 7 Lecture 7-2: Arrays as Parameters reading: , 3.3 self-checks: Ch. 7 #5, 8,
Exercise 1 Suppose C is a class that implements interfaces I and J. Which of the following Requires a type cast? C c = ……? I i = …..? J j = …..? c =
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.
Background. 7 月 20 日 Background 7 月 20 日 我原以为这是平凡的一天.
Lecture 15.1 Static Methods and Variables. © 2006 Pearson Addison-Wesley. All rights reserved Static Methods In Java it is possible to declare.
METHOD OVERRIDING Sub class can override the methods defined by the super class. Overridden Methods in the sub classes should have same name, same signature.
METHOD OVERRIDING 1.Sub class can override the methods defined by the super class. 2.Overridden Methods in the sub classes should have same name, same.
Ade Azurat, Advanced Programming 2004 (Based on LYS Stefanus’s slides) Advanced Programming 2004, Based on LYS Stefanus’s slides Slide 2.1 Multithreading.
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.
Methods. int month; int year class Month Defining Classes A class contains data declarations (static and instance variables) and method declarations (behaviors)
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.
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.
Problem Solving #3: JVM ICS Outline Review of Key Topics Review of Key Topics Problem 1 Problem 1 Problem 2 Problem 2 Problem 3 Problem 3 Problem.
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.
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.
CMSC 341 Introduction to Java Based on tutorial by Rebecca Hasti at
Inheritance #1 First questions Similar to Python? What about visibility and encapsulation? – can an object of the child class access private members.
Java Object and Class in Java. Java Naming conventions A naming convention is a rule to follow as you decide what to name your identifiers e.g. class,
CSC3170 Introduction to Database Systems
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.
Puzzle 3 1  Write the class Enigma, which extends Object, so that the following program prints false: public class Conundrum { public static void main(String[]
Ics202 Data Structures. class Array { protected Object[] data; protected int base; public Array (int n, int m) { data = new Object[n]; base = m; } public.
© Keren Kalif Advanced Java Topics Written by Keren Kalif, Edited by Liron Blecher.
Example: O-O Payroll Program (§11.4) Object-Oriented Design Behavior. Our program should read a sequence of employees from an input file, ( managers, secretaries,
WEEK 2 Introduction to Java II CSE 252 Principles of Programming Languages LAB SECTION.
JAVA PROGRAMMING PART III. METHOD STATEMENT Form of method statement [ ] [static] ( [ ]) { } Example public static void main(String args[])
Recitation 8 User Defined Classes Part 2. Class vs. Instance methods Compare the Math and String class methods that we have used: – Math.pow(2,3); – str.charAt(4);
C OMP 401 R EFLECTION AND A CTION O BJECTS Instructor: Prasun Dewan.
CSC Java Programming, Fall, 2008 Week 3: Objects, Classes, Strings, Text I/O, September 11.
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.”
COMP Inheritance and Polymorphism Yi Hong June 09, 2015.
Cs205: engineering software university of virginia fall 2006 Programming Exceptionally David Evans
Programming in Java Transitioning from Alice. Becomes not myFirstMethod but …. public static void main (String[] arg) { // code for testing classes goes.
Chapter 7: Cloning and RTTI
Summary prepared by Kirk Scott
Java Memory Management
Java Memory Management
CSE 413, Autumn 2002 Programming Languages
EE 422C Java Reflection re·flec·tion rəˈflekSH(ə)n/ noun
The this Reference The this reference allows an object to refer to itself That is, the this reference, used inside a method, refers to the object through.
JAVA Constructors.
A Java Application public class Hello { public static void main(String [] args) { System.out.println("Hello, World!"); } } public class.
A Java Application public class Hello { public static void main(String [] args) { System.out.println("Hello, World!"); } } public class.
Some Examples Reflection is used for many things:
Presentation transcript:

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

Examine an object’s class at runtime 01 package myreflection; 02 import java.lang.reflect.Method; public class ReflectionHelloWorld { 05 public static void main(String[] args){ 06 Foo f = new Foo(); 07 System.out.println(f.getClass().getName()); 08 } 09} 10 11class Foo { 12 public void print() { 13 System.out.println("abc"); 14 } 15} Output myreflection.Foo

Invoke method on unknown object 01package myreflection; 02import java.lang.reflect.Method; 03 public class ReflectionHelloWorld { 04 public static void main(String[] args){ 05 Foo f = new Foo(); 06 Method method; 07 try { 08 method = f.getClass().getMethod("print", new Class [0]); 09 method.invoke(f); 10 } catch (Exception e) { 11 e.printStackTrace(); 12 } } } 13 14class Foo { 15 public void print() { 16 System.out.println("abc"); 17 } } Output abc

Create object from Class instance 01 package myreflection; 02 public class ReflectionHelloWorld { 03 public static void main(String[] args){ 04 //create instance of "Class" 05 Class c = null; 06 try{ 07 c=Class.forName("myreflection.Foo"); 08 }catch(Exception e){ 09 e.printStackTrace(); 10 } 11 //create instance of "Foo" 12 Foo f = null; 13 try { 14 f = (Foo) c.newInstance(); 15 } catch (Exception e) { 16 e.printStackTrace(); 17 } f.print(); 20 } 21 } class Foo { 24 public void print() { 25 System.out.println("abc"); 26 } 27 }

Get constructor and create instance 01 package myreflection; 02 import java.lang.reflect.Constructor; 03 public class ReflectionHelloWorld { 04 public static void main(String[] args){ 05 //create instance of "Class" 06 Class c = null; 07 try{ 08 c=Class.forName("myreflection.Foo"); 09 }catch(Exception e){ 10 e.printStackTrace(); 11 } 12 //create instance of "Foo" 13 Foo f1 = null; 14 Foo f2 = null; 15 //get all constructors 16 Constructor cons[] = c.getConstructors(); 17 try { 18 f1 = (Foo) cons[0].newInstance(); 19 f2 = (Foo) cons[1].newInstance("abc"); 20 } catch (Exception e) { 21 e.printStackTrace(); 22 } 23 f1.print(); 24 f2.print(); 25 } 26 } 27 class Foo { 28 String s; 29 public Foo(){} public Foo(String s){ 32 this.s=s; 33 } public void print() { 36 System.out.println(s); 37 } 38 } Output null abc

Change array size though reflection 01 package myreflection; 02 import java.lang.reflect.Array; public class ReflectionHelloWorld { 05 public static void main(String[] args) { 06 int[] intArray = { 1, 2, 3, 4, 5 }; 07 int[] newIntArray = (int[]) changeArraySize(intArray, 10); 08 print(newIntArray); 09 String[] atr = { "a", "b", "c", "d", "e" }; 10 String[] str1 = (String[]) changeArraySize(atr, 10); 11 print(str1); 12 } // change array size 15 public static Object changeArraySize(Object obj, int len) { 16 Class arr = obj.getClass().getComponentType(); 17 Object newArray = Array.newInstance(arr, len); //do array copy 20 int co = Array.getLength(obj); 21 System.arraycopy(obj, 0, newArray, 0, co); 22 return newArray; 23 } 24 // print 25 public static void print(Object obj) { 26 Class c = obj.getClass(); 27 if (!c.isArray()) { 28 return; 29 } System.out.println("\nArray length: " + Array.getLength(obj)); for (int i = 0; i < Array.getLength(obj); i++) { 34 System.out.print(Array.get(obj, i) + " "); 35 } 36 } 37 } Output Array length: Array length: 10 a b c d e null null null null null