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.

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.
Designing an ADT The design of an ADT should evolve naturally during the problem-solving process Questions to ask when designing an ADT What data does.
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
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.
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.
What is a class? a class definition is a blueprint to build objects its like you use the blueprint for a house to build many houses in the same way you.
1 Java object model Part 3: Serialization & Reflection.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 4 Defining Your Own Classes.
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.
CMSC 202 Interfaces. 11/20102 Classes and Methods When a class defines its methods as public, it describes how the class user interacts with the method.
Java and C++, The Difference An introduction Unit - 00.
220 FINAL TEST REVIEW SESSION Omar Abdelwahab. INHERITANCE AND POLYMORPHISM Suppose you have a class FunClass with public methods show, tell, and smile.
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.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
The Reflection Lucielle Mendez Antonio Bologna.
CIS 644 Aug. 25, 1999 tour of Java. First … about the media lectures… we are experimenting with the media format please give feedback.
Inheritance. Introduction Inheritance is one of the cornerstones of object-oriented programming because it allows the creation of hierarchical classifications.
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!
Utilities (Part 2) Implementing static features 1.
Checking Equality of Reference Variables. Arrays and objects are both “reference” types n They are allocated a chunk of memory in the address space n.
Reflection in Java Bibliografie: Sun: The Java Tutorials – The Reflection API Java programming.
Methods in Java. Program Modules in Java  Java programs are written by combining new methods and classes with predefined methods in the Java Application.
© Keren Kalif Advanced Java Topics Written by Keren Kalif, Edited by Liron Blecher.
OOP in Java : © W. Milner 2005 : Slide 1 Java and OOP Part 2 – Classes and objects.
Introduction to Java Lecture Notes 3. Variables l A variable is a name for a location in memory used to hold a value. In Java data declaration is identical.
Session 7 Methods Strings Constructors this Inheritance.
Java - Classes JPatterson. What is a class? public class _Alpha { public static void main(String [] args) { } You have been using classes all year – you.
CMSC 341 Java Packages, Classes, Variables, Expressions, Flow Control, and Exceptions.
C OMP 401 R EFLECTION AND A CTION O BJECTS Instructor: Prasun Dewan.
Interfaces and Inner Classes
CSI 3125, Preliminaries, page 1 Overloading Methods In Java it is possible to define two or more methods within the same class that share the same name,
More on Objects Mehdi Einali Advanced Programming in Java 1.
Peyman Dodangeh Sharif University of Technology Spring 2014.
CSCE 314 Programming Languages Reflection Dr. Hyunyoung Lee 1.
Reflection Bibliografie: Sun: The Java Tutorials – The Reflection API IBM developerWorks:
Access Specifier. Anything declared public can be accessed from anywhere. Anything declared private cannot be seen outside of its class. When a member.
Chapter 6 - More About Problem Domain Classes1 Chapter 6 More About Problem Domain Classes.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
CSE 331 Reflection slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia
© 2006 Pearson Addison-Wesley. All rights reserved 1-1 Chapter 1 Review of Java Fundamentals.
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.”
LECTURE 8: EXCEPTIONS CSC 212 – Data Structures. Error Handling Goals  What should we do when an error occurs?  Should alert system to the error  May.
Topics Instance variables, set and get methods Encapsulation
OOP Basics Classes & Methods (c) IDMS/SQL News
Reflection Mehdi Einali Advanced Programming in Java 1.
Reflections CSC207 – Software Design. Background Turing's great insight: programs are just another kind of data. Source code is text that is interpreted.
JAVA ACCESS MODIFIERS. Access Modifiers Access modifiers control which classes may use a feature. A classes features are: - The class itself - Its member.
Sadegh Aliakbary Sharif University of Technology Fall 2010.
Modern Programming Tools And Techniques-I
Chapter 7: Cloning and RTTI
Sixth Lecture ArrayList Abstract Class and Interface
NESTED CLASSES REFLECTION PROXIES.
Java and OOP Part 5 – More.
Examples of Classes & Objects
CSE 413, Autumn 2002 Programming Languages
Presentation on Object Oriented programming Topic
EE 422C Java Reflection re·flec·tion rəˈflekSH(ə)n/ noun
Computer Science II Exam 1 Review.
Advanced Programming in Java
Java Programming Language
Classes & Objects: Examples
CMPE212 – Reminders Assignment 3 due next Friday.
Java Programming Language
CSCE 314: Programming Languages Dr. Dylan Shell
Reflection in Java By: Zachary Cava.
Presentation transcript:

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 Reflection API is supported by the classes in the java.lang.reflect package. Within the limits imposed by Java security manager, one can find out what constructors, methods, and fields (variables) a class has. Classes in Java are represented at runtime by instances of the java.lang.Class class. There’s a Class object for every class. The Class object is the basis for reflection.

slide 11.2 Advanced Programming 2004, based on LY Stefanus’s Slides the Class class The Class reference associated with a particular object can be obtained with the getClass() method: String myString = ”hello”; Class myClass = myString.getClass(); We can also get the Class reference for a particular class using the.class notation: Class myClass = myString.class; One thing we can do with the Class object is ask for the name of the object’s class: System.out.println(myClass.getName()); //”java.lang.String”

slide 11.3 Advanced Programming 2004, based on LY Stefanus’s Slides A Class object can be asked to produce a new instance of its type of object. try { String s2 = (String) myClass.newInstance(); } catch ( InstantiationException e ) {... } catch ( IllegalAccessException e ) {... } newInstance() has a return type of Object. InstantiationException indicates that we’re trying to instantiate an abstract class or an interface. IllegalAccessException is a more general exception that indicates we can’t access a constructor for the object.

slide 11.4 Advanced Programming 2004, based on LY Stefanus’s Slides We can look up a class by name. forName() is a static method of Class class that returns a Class object given its name as a String: try { Class abcClass = Class.forName(”abc”); } catch ( ClassNotFoundException e ) {... } ClassNotFoundException is thrown if the class can’t be located.

slide 11.5 Advanced Programming 2004, based on LY Stefanus’s Slides The Class Objects of Primitive Types Represented by special static TYPE fields of their respective wrapper classes. For example, use Integer.TYPE for the Class object of int; use Double.TYPE for the Class object of double.

slide 11.6 Advanced Programming 2004, based on LY Stefanus’s Slides Methods in the Class class Field[] getFields( ) –Get all public variables, including inherited ones. Field getField( String name ) –Get the specified public variable, which may be inherited. Field[] getDeclaredFields( ) –Get all public and nonpublic variables declared in this class (not including those inherited) Field getDeclaredField( String name ) –Get the specified variable, public or nonpublic, declared in this class (inherited variables not considered)

slide 11.7 Advanced Programming 2004, based on LY Stefanus’s Slides Method[] getMethods( ) –Get all public methods, including inherited ones. Method getMethod( String name, Class[] argumentTypes) –Get the specified public method whose arguments match the types listed in argumentTypes. The method may be inherited. Method[] getDeclaredMethods( ) –Get all public and nonpublic methods declared in this class, not including those inherited. Method getDeclaredMethod( String name, Class[] argumentTypes) –Get the specified method, public or nonpublic, whose arguments match the types listed in argumentTypes. The inherited methods are not considered.

slide 11.8 Advanced Programming 2004, based on LY Stefanus’s Slides Constructor[] getConstructors( ) –Get all public constructors of this class. Constructor getConstructor(Class[] argumentTypes) –Get the public constructor whose arguments match the types listed in argumentTypes. Constructor[] getDeclaredConstructors( ) –Get all public and nonpublic constructors of this class. Constructor getDeclaredConstructor(Class[] argumentTypes) –Get the constructor, public or nonpublic, whose arguments match the types listed in argumentTypes.

slide 11.9 Advanced Programming 2004, based on LY Stefanus’s Slides Exercise 1) Write a program which accepts a name of a class and then print the information on –which class (or classes) the given class extends and –which interface (or interfaces) the class implements, hierarchically up to the class Object. (ShowInfoClass.java) 2) Write a program to list all the methods declared in a given class. The name of this class is given as the input to the program. (ListMethods.java)

slide Advanced Programming 2004, based on LY Stefanus’s Slides Accessing Fields of a Class The class java.lang.reflect.Field represents static variables and instance variables. The class Field has a full set of overloaded accessor methods for all the primitive types (for example, getInt() and setInt(), getBoolean() and setBoolean()) and get() and set() methods for accessing members that are object references. All the data access methods of Field take a reference to the particular object instance that we want to access. Check out an example: (Note that we're accessing the balance field at runtime.)

slide Advanced Programming 2004, based on LY Stefanus’s Slides AccessField.java import java.lang.reflect.*; public class AccessField { public static void main(String[] arg) { BankAcc ba = new BankAcc(); try { Field balanceField = BankAcc.class.getDeclaredField("balance"); //read the balance field of ba double myBalance = balanceField.getDouble(ba); System.out.println("Initially balance contains " + myBalance); //change it balanceField.setDouble(ba, 600); System.out.println("Now balance contains " + balanceField.getDouble(ba));

slide Advanced Programming 2004, based on LY Stefanus’s Slides } catch( NoSuchFieldException e1 ) { System.err.println(e1); } catch( IllegalAccessException e2 ) { System.err.println(e2); } class BankAcc { public double balance; //private double balance; }

slide Advanced Programming 2004, based on LY Stefanus’s Slides Accessing Methods The class java.lang.reflect.Method represents a static or instance method. Subject to the normal security rules, a Method object's invoke() method can be used to call the underlying object's method with specified arguments. This is something like a method pointer in a language such as C++. The first argument to invoke() is the object on which we want to invoke the method. If the method is static, there is no object, so we set the first argument to null. The second argument is an array of objects to be passed as arguments to the method.

slide Advanced Programming 2004, based on LY Stefanus’s Slides Exercise Write a Java application that takes as command-line arguments the name of a class and the name of a method to invoke. Assume that the method is static and takes one argument. (Invoke.java)

slide Advanced Programming 2004, based on LY Stefanus’s Slides C:\advprog> java Invoke java.lang.Math sqrt 25.0 Invoked static method: sqrt of class: java.lang.Math with argument: 25.0 Result: 5.0

slide Advanced Programming 2004, based on LY Stefanus’s Slides Accessing Constructors The java.lang.reflect.Constructor class represents an object constructor that accepts arguments. We can use it, subject to the security rules, to create a new instance of an object. Example:

slide Advanced Programming 2004, based on LY Stefanus’s Slides import java.lang.reflect.*; import java.util.*; import java.text.*; class AccessConstructor { public static void main( String [] args ) { try { Constructor c = Date.class.getConstructor(new Class[] {Long.TYPE}); Object ob = c.newInstance(new Object[] {new Long(new Date().getTime())} ); DateFormat fmt = DateFormat.getDateInstance(DateFormat.FULL); System.out.println(fmt.format((Date)ob)); } catch ( InstantiationException e ) {//the class is abstract System.err.println(e); } catch ( NoSuchMethodException e2 ) {//that constructor doesn't exist System.err.println(e2); } catch ( IllegalAccessException e3 ) { // we don't have permission to create an instance System.err.println(e3); } catch ( InvocationTargetException e4 ) { // an exception occurred while invoking that constructor System.err.println(e4); }