Object Oriented Programming in Java Lecture 13. Java Reflection Reflection is a feature unique to Java that allows an executing program to examine or.

Slides:



Advertisements
Similar presentations
Introduction to Java Reflection
Advertisements

Reflection Reflection is the ability of a program to examine and modify the structure and behavior of an object at runtime.
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.
CERTIFICATION OBJECTIVES Use Class Members Develop Wrapper Code & Autoboxing Code Determine the Effects of Passing Variables into Methods Recognize when.
1 Lecture 11 Interfaces and Exception Handling from Chapters 9 and 10.
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.
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.
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.
Java Virtual Machine (JVM). Lecture Objectives Learn about the Java Virtual Machine (JVM) Understand the functionalities of the class loader subsystem.
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.
03G-1 Reflection In Java For every loaded class, the Java Runtime Environment (JRE) maintains an associated Class object The Class object “ reflects ”
1 Java object model Part 3: Serialization & Reflection.
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.
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.
1 Chapter 8 Objects and Classes. 2 Motivations After learning the preceding chapters, you are capable of solving many programming problems using selections,
Reflection API Faculty of Information Technologies Industrial University of Ho Chi Minh City Java Programming Course 1.
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
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.
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.
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!
APCS Java AB 2004 Review of CS1 and CS2 Review for AP test #1 Sources: 2003 Workshop notes from Chris Nevison (Colgate University) AP Study Guide to go.
5-Aug-2002cse Arrays © 2002 University of Washington1 Arrays CSE 142, Summer 2002 Computer Programming 1
Inheritance and Polymorphism Daniel Liang, Introduction to Java Programming.
Review of ICS 102. Lecture Objectives To review the major topics covered in ICS 102 course Refresh the memory and get ready for the new adventure of ICS.
Reflection in Java Bibliografie: Sun: The Java Tutorials – The Reflection API Java programming.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
CMSC 341 Java Packages, Classes, Variables, Expressions, Flow Control, and Exceptions.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 9 Inheritance and.
C OMP 401 R EFLECTION AND A CTION O BJECTS Instructor: Prasun Dewan.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
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:
COM S 228 Introduction to Data Structures Instructor: Ying Cai Department of Computer Science Iowa State University Office: Atanasoff.
CSI 3125, Preliminaries, page 1 Inheritance. CSI 3125, Preliminaries, page 2 Inheritance Using inheritance, can create a general class that defines traits.
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.”
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.
Object Oriented Programming Lecture 2: BallWorld.
Modern Programming Tools And Techniques-I
Chapter 7: Cloning and RTTI
Sixth Lecture ArrayList Abstract Class and Interface
NESTED CLASSES REFLECTION PROXIES.
Java Programming Course
Java as a Dynamic Language
Java Primer 1: Types, Classes and Operators
CSE 413, Autumn 2002 Programming Languages
EE 422C Java Reflection re·flec·tion rəˈflekSH(ə)n/ noun
Advanced Programming in Java
What is Reflection? Some Definitions….
Some Examples Reflection is used for many things:
What is Reflection? Some Definitions….
CSCE 314: Programming Languages Dr. Dylan Shell
Reflection in Java By: Zachary Cava.
Presentation transcript:

Object Oriented Programming in Java Lecture 13

Java Reflection Reflection is a feature unique to Java that allows an executing program to examine or “introspect” upon itself, and manipulate properties of the program. For example, it is possible for a Java class to get the names of its members and display them. There is no way in C, C++ or other languages to get information about functions defined within a program. Reflection Classes are found in java.lang.reflect.

An Example import java.lang.reflect.*; public class GetMethods { public static void main(String[ ] args) { try { Class a = Class.forName(args[0]); Method meth[ ] = a.getDeclaredMethods(); for (int i = 0; i < meth.length; i++) System.out.println(meth[ i ].toString()); } catch (Throwable exc) { System.err.println(exc); } Examples: invoke GetMethods on java.util.Stack, java.lang.String, and user-defined class LinkChecker. > java GetMethods java.util.Stack

Using Reflection Classes: 3 Steps 1. Obtain a java.lang.Class object for the class you want to manipulate. For example: Class a = Class.forName(“java.lang.String”); gets the class object for String. Class b = int.class; gets class information on types such as int.

Using Reflection Classes: 3 Steps 2. Call a method such as getDeclaredMethods to get a list of methods declared in a class: Class a = Class.forName(“java.lang.String”); Method meth[ ] = a.getDeclaredMethods(); 3. Use the reflection API to manipulate this list: Calling toString() for each element in the meth array displays all methods declared in String.

The Class class To find out about a class, first get its Class object –If you have an object obj, you can get its class object with Class c = obj.getClass(); –You can get the class object for the superclass of a Class c with Class sup = c.getSuperclass(); –If you know the name of a class (say, Button ) at compile time, you can get its class object with Class c = Button.class; –If you know the name of a class at run time (in a String variable str ), you can get its class object with Class c = Class.forName(str);

Getting the class name If you have a class object c, you can get the name of the class with c.getName() getName returns the fully qualified name; that is, Class c = Button.class; String s = c.getName(); System.out.println(s); will print java.awt.Button Class Class and its methods are in java.lang, which is always imported and available

Getting all the superclasses getSuperclass() returns a Class object (or null if you call it on Object, which has no superclass) The following code is from the Sun tutorial: static void printSuperclasses(Object o) { Class subclass = o.getClass(); Class superclass = subclass.getSuperclass(); while (superclass != null) { String className = superclass.getName(); System.out.println(className); subclass = superclass; superclass = subclass.getSuperclass(); } }

Getting the class modifiers I A Class object has an instance method getModifiers() that returns an int To “decipher” the int result, we need methods of the Modifier class, which is in java.lang.reflect, so: import java.lang.reflect.*; Now we can do things like: if (Modifier.isPublic(m)) { System.out.println("public"); }

Getting the class modifiers II Modifier contains these methods (among others): –public static boolean isAbstract(int) –public static boolean isFinal(int) –public static boolean isInterface(int) –public static boolean isPrivate(int) –public static boolean isProtected(int) –public static boolean isPublic(int) –public static String toString(int) This will return a string such as "public final synchronized strictfp"

Getting interfaces A class can implement zero or more interfaces getInterfaces() returns an array of Class objects –These are the interfaces implemented by the class More code from Sun:  static void printInterfaceNames(Object o) { Class c = o.getClass(); Class[ ] theInterfaces = c.getInterfaces(); for (int i = 0; i < theInterfaces.length; i++) { String interfaceName = theInterfaces[i].getName(); System.out.println(interfaceName); } } Note that zero-length arrays are perfectly legal in Java

Examining classes and interfaces The class Class represents both classes and interfaces To determine if a given Class object c is an interface, use c.isInterface() To find out more about a class object, use: –getModifiers() –getFields() // "fields" == "instance variables" –getConstructors() –getMethods() –isArray()

Getting Field s public Field[] getFields() throws SecurityException –Returns an array of public Fields (variables) –The length of the array may be zero –The fields are not returned in any particular order –Both locally defined and inherited instance variables are returned, but not static variables public Field getField(String name) throws NoSuchFieldException, SecurityException –Returns the named public Field –If no immediate field is found, the superclasses and interfaces are searched recursively

Using Field s, I If f is a Field object, then –f.getName() returns the simple name of the field –f.getType() returns the type ( Class ) of the field –f.getModifiers() returns the Modifier s of the field –f.toString() returns a String containing access modifiers, the type, and the fully qualified field name Example: public java.lang.String Person.name –f.getDeclaringClass() returns the Class in which this field is declared

Using Field s, II The values of the fields of an object obj may be accessed with: –boolean f.getBoolean(obj), int f.getInt(obj), double f.getDouble(obj), etc., return the value of the field, assuming it is that type or can be widened to that type –Object f.get(obj) returns the value of the field, assuming it is an Object –void f.set(obj, value), void f.setBoolean(obj, bool), void f.setInt(obj, i), void f.getDouble(obj, d), etc. set the value of a field

Constructors If c is a Constructor object, then –c.getName() returns the name of the constructor, as a String (this is the same as the name of the class) –c.getDeclaringClass() returns the Class in which this constructor is declared –c.getModifiers() returns the Modifier s of the constructor –c.getParameterTypes() returns an array of Class objects, in declaration order –c.newInstance(Object[] initargs) creates and returns a new instance of class c Arguments that should be primitives are automatically unwrapped as needed

Methods public Method[] getMethods() throws SecurityException –Returns an array of Method objects –These are the public member methods of the class or interface, including inherited methods –The methods are returned in no particular order public Method getMethod(String name, Class[] parameterTypes) throws NoSuchMethodException, SecurityException

Method methods, I getDeclaringClass() –Returns the Class object representing the class or interface that declares the method represented by this Method object getName() –Returns the name of the method represented by this Method object, as a String getModifiers() –Returns the Java language modifiers for the method represented by this Method object, as an integer getParameterTypes() –Returns an array of Class objects that represent the formal parameter types, in declaration order, of the method represented by this Method object

Method methods, II getReturnType() –Returns a Class object that represents the formal return type of the method represented by this Method object toString() –Returns a String describing this Method (typically pretty long) public Object invoke(Object obj, Object[] args) –Invokes the underlying method represented by this Method object, on the specified object with the specified parameters –Individual parameters are automatically unwrapped to match primitive formal parameters

Arrays I To determine whether an object obj is an array, –Get its class c with Class c = obj.getClass(); –Test with c.isArray() To find the type of components of the array, –c.getComponentType() Returns null if c is not the class of an array There is an Array class in java.lang.reflect that provides static methods for working with arrays

Arrays II To create an array, Array.newInstance(Class componentType, int size) –This returns, as an Object, the newly created array You can cast it to the desired type if you like –The componentType may itself be an array This would create a multiply-dimensioned array The limit on the number of dimensions is usually 255 Array.newInstance(Class componentType, int[] size) –This returns, as an Object, the newly created multidimensional array (with size.length dimensions)

Arrays III To get the value of array elements, –Array.get(Object array, int index) returns an Object –Array.getBoolean(Object array, int index) returns a boolean –Array.getByte(Object array, int index) returns a byte –etc. To store values into an array, –Array.set(Object array, int index, Object value) –Array.setBoolean(Object array, int index, boolean z) –Array.setByte(Object array, int index, byte b) –etc.

Applications of Reflection Parametric Programming Aspect Oriented Programming …