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.

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.
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
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.
JVM-1 Java Virtual Machine Reading Assignment: Chapter 1: All Chapter 3: Sections.
Algorithm Programming Java Reflection Mechanism Bar-Ilan University תשס"ז Moshe Fresko.
Exceptions Three categories of errors: Syntax errors Runtime errors Logic errors Syntax errors: rules of the language have not been followed. Runtime error:
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.
JVM-1 Java Virtual Machine Reading Assignment: Chapter 1: All Chapter 3: Sections.
Java Virtual Machine (JVM). Lecture Objectives Learn about the Java Virtual Machine (JVM) Understand the functionalities of the class loader subsystem.
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 ”
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.
Chapter 12 Inheritance and Exceptions Lecture Slides to Accompany An Introduction to Computer Science Using Java (2nd Edition) by S.N. Kamin, D. Mickunas,
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.
Session One Introduction. Personal Introduction Role of programmers Robot Examination HUD & HID Uploading Code.
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.
Course contents Basic concepts –What is software architecture ? Fundamental architectural styles –Pipes and filters –Layers –Blackboard –Event-driven Architectural.
Lecture 2 Exception handling Advanced Java Programming 1 dr inż. Wojciech Bieniecki
Java Introduction 密碼學與應用 海洋大學資訊工程系 丁培毅.
Reflection in Java Bibliografie: Sun: The Java Tutorials – The Reflection API Java programming.
© Keren Kalif Advanced Java Topics Written by Keren Kalif, Edited by Liron Blecher.
Chapter 8 Objects and Classes Object Oriented programming Instructor: Dr. Essam H. Houssein.
Chapter 5 Objects and Classes Inheritance. Solution Assignments 3 & 4 Review in class…..
1 Abstract Classes and Interfaces. 2 The abstract Modifier  The abstract class –Cannot be instantiated –Should be extended and implemented in subclasses.
CS884 (Prasad)java11Extn1 Java 1.1 Extensions Nested classes static public/protected/private.
Java Class Structure. Class Structure package declaration import statements class declaration class (static) variable declarations* instance variable.
Programming With Java ICS201 University Of Ha’il1 Chapter 7 Inheritance.
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
Java Programming: From Problem Analysis to Program Design, 3e Chapter 11 Inheritance and Polymorphism.
CSCE 314 Programming Languages Reflection Dr. Hyunyoung Lee 1.
Interfaces F What is an Interface? F Creating an Interface F Implementing an Interface F What is Marker Interface?
Reflection Bibliografie: Sun: The Java Tutorials – The Reflection API IBM developerWorks:
Recitation 3 2D Arrays, Exceptions. 2D arrays 2D Arrays Many applications have multidimensional structures: ●Matrix operations ●Collection of lists ●Board.
Exceptions Handling Prepared by: Ligemm Mae del Castillo.
Chapter 11: Advanced Inheritance Concepts. Objectives Create and use abstract classes Use dynamic method binding Create arrays of subclass objects Use.
Inheritance ndex.html ndex.htmland “Java.
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.
POLYMORPHISM Chapter 6. Chapter Polymorphism  Polymorphism concept  Abstract classes and methods  Method overriding  Concrete sub classes and.
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
Reflections CSC207 – Software Design. Background Turing's great insight: programs are just another kind of data. Source code is text that is interpreted.
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;
Lecture 5:Interfaces and Abstract Classes Michael Hsu CSULA.
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.
Lecture 6:Interfaces and Abstract Classes Michael Hsu CSULA.
Course contents Basic concepts Fundamental architectural styles
Chapter 7: Cloning and RTTI
Sixth Lecture ArrayList Abstract Class and Interface
NESTED CLASSES REFLECTION PROXIES.
Java Programming Course
Java as a Dynamic Language
CSE 413, Autumn 2002 Programming Languages
Week 8 Lecture -3 Inheritance and Polymorphism
Computer Science II Exam 1 Review.
Рефлексия Макаревич Л. Г..
Interface.
Java Programming Language
Inheritance Inheritance is a fundamental Object Oriented concept
What is Reflection? Some Definitions….
What is Reflection? Some Definitions….
CSCE 314: Programming Languages Dr. Dylan Shell
Presentation transcript:

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 support may not be prioritized.

3 Run-time introspection If you are writing a class browser, debug system, IDE environment (Eclipse). Discover which methods/constructors are available in an object or class. Discover attributes/fields Discover super classes and implemented interfaces Instantiate objects from class name And more…

4 Getting the “Class object” Taste on it… confused? An object that represents a class… For each class, the Java Runtime Environment (JRE) maintains an immutable Class object that contains information about the class. A Class object represents, or reflects, the class. Class objects not only represent classes but also interfaces.

5 Confusion continued…

6 Examples If an instance of the class is available… Class c = mystery.getClass(); retrieve the Class object for the superclass TextField t = new TextField(); Class c = t.getClass(); Class s = c.getSuperclass(); If you know the name of the class at compile time, Class c = java.awt.Button.class; If the class name is unknown at compile time, but available at runtime Class c = Class.forName(strg);

7 Getting the Class Name import java.awt.Button; class SampleName { public static void main(String[] args) { Button b = new Button(); printName(b); } static void printName(Object o) { Class c = o.getClass(); String s = c.getName(); System.out.println(s); } } What will be printed?

8 Discovering Class Modifiers public final class Coordinate {int x, int y, int z} class SampleModifier { public static void main(String[] args) { String s = new String(); printModifiers(s); } public static void printModifiers(Object o) { Class c = o.getClass(); int m = c.getModifiers(); if (Modifier.isPublic(m)) System.out.println("public"); if (Modifier.isAbstract(m)) System.out.println("abstract"); if (Modifier.isFinal(m)) System.out.println("final"); } } Output?

9 Finding the superclass To determine the superclass of a class, you invoke the getSuperclass method. This method returns a Class object representing the superclass, or returns null if the class has no superclass. To identify all ancestors of a class, call getSuperclass iteratively until it returns null.

10 Example import java.lang.reflect.*; import java.awt.*; class SampleSuper { public static void main(String[] args) { Button b = new Button(); printSuperclasses(b); } 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(); } } }

11 Interfaces An interface is similar to a superclass and is thus as important as such. The class below implements two interfaces. public class RandomAccessFile implements DataOutput, DataInput

12 Example class SampleInterface { public static void main(String[] args) { try { RandomAccessFile r=new RandomAccessFile("fil", "r"); printInterfaceNames(r); } catch (IOException e) { System.out.println(e); } } 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); } } }

13 Examining Interfaces The isInterface() method helps in distinguishing between interfaces and classes.

14 Example class SampleCheckInterface { public static void main(String[] args) { Class observer = Observer.class; Class observable = Observable.class; verifyInterface(observer); verifyInterface(observable); } static void verifyInterface(Class c) { String name = c.getName(); if (c.isInterface()) { System.out.println(name + " is an interface."); } else { System.out.println(name + " is a class."); } } } Output?

15 Identifying Class Fields You might want to find out what fields belong to a particular class, by invoking the getFields() method on a Class object.

16 Example class SampleField { public static void main(String[] args) { GridBagConstraints g = new GridBagConstraints(); printFieldNames(g); } static void printFieldNames(Object o) { Class c = o.getClass(); Field[] publicFields = c.getFields(); for (int i = 0; i < publicFields.length; i++) { String fieldName = publicFields[i].getName(); Class typeClass = publicFields[i].getType(); String fieldType = typeClass.getName(); System.out.println("Name: " + fieldName + ", Type: " + fieldType); } } }

17 Is the field an array? Use the Class.isArray() method. Field[] publicFields = targetClass.getFields(); for (int i = 0; i < publicFields.length; i++) { String fieldName = publicFields[i].getName(); Class typeClass = publicFields[i].getType(); String fieldType = typeClass.getName(); if (typeClass.isArray()) { System.out.println("Name: " + fieldName + ", Type: " + fieldType); } }

18 Retrieving Component Types Integer[] is an array with component type Integer The component type of a multidimensional array is an array. Integer[][] m = new Integer[10][10]; In the line above the component type of m is… Integer[]

19 Class Constructors Information about constructors is retrieved by calling the getConstructors() method. Returns an Array of Constructor objects

20 Example class SampleConstructor { public static void main(String[] args) { Rectangle r = new Rectangle(); showConstructors(r); } static void showConstructors(Object o) { Class c = o.getClass(); Constructor[] theConstr = c.getConstructors(); for (int i = 0; i < theConstr.length; i++) { System.out.print("( "); Class[] parameterTypes = theConstr[i].getParameterTypes(); for (int k = 0; k < parameterTypes.length; k++) { String parameterString = parameterTypes[k].getName(); System.out.print(parameterString + " "); } System.out.println(")"); } } }

21 Methods Methods are retrieved in a similar manner, in an Array.

22 Manipulating Objects With the reflection API you may also Create objects and Arrays of objects Get and set field values Invoke methods

23 “Real Life” Example from the IFOR navigation project Ini file: load.rangearrayproxy = com.ifor.proxy.RangeArrayProxy load.tycoradararrayproxy1 = com.ifor.proxy.RangeArrayProxy load.tycoradararrayproxy2 = com.ifor.proxy.RangeArrayProxy load.map2dproxy = com.ifor.proxy.Obstacle2DProxy

24 Example cont. Java: public Loadable loadableFactory(String className) { Loadable object = null; try { Class classDefinition = Class.forName(className); object = (Loadable)classDefinition.newInstance(); } catch (IllegalArgumentException ex) { logger.log(this, "className + " " + ex, Logger.EXCEPTION);} catch (InstantiationException ex) { logger.log(this, "className + " " + ex, Logger.EXCEPTION);} catch (IllegalAccessException ex) { logger.log(this, "className + " " + ex, Logger.EXCEPTION);} catch (ClassNotFoundException ex) { logger.log(this, "className + " " + ex, Logger.EXCEPTION);} return object; }

25 Reflection classes The 7 classes that compose the reflection API: Object: Provides the getClass() method. Class: Reflects Classes and Interfaces. Array: Provides static methods to dynamically create and access arrays. Constructor: Allows you to instantiate a class dynamically. Field: Allows you to invoke the method dynamically. Method: Provides access to a single method on a class or interface Modifier: Allows you to get information about the access modifiers of a class and its members. Object and Class are part of the java.lang package, while the rest is part of java.lang.reflect package.