Advanced Java Programming Lecture 5 Reflection dr hab. Szymon Grabowski dr inż. Wojciech Bieniecki

Slides:



Advertisements
Similar presentations
Composition CMSC 202. Code Reuse Effective software development relies on reusing existing code. Code reuse must be more than just copying code and changing.
Advertisements

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.
ECE 750 Topic 8 Meta-programming languages, systems, and applications Load-time structural reflection in Java – Shigeru Chiba, 2000 May 27, 2004 Shimin.
Lab Information Security Using Java (Review) Lab#0 Omaima Al-Matrafi.
Abstract Data Types Data abstraction, or abstract data types, is a programming methodology where one defines not only the data structure to be used, but.
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
Road Map Introduction to object oriented programming. Classes
COMP171 Data Structure & Algorithm Tutorial 1 TA: M.Y.Chan.
Principles of Object-Oriented Software Development The language 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.
Reflection (Reflexion in British English ) Mo Alkhafaji.
How is Java different from other languages Less than you think: –Java is an imperative language (like C++, Ada, C, Pascal) –Java is interpreted (like LISP,
1 Java object model Part 3: Serialization & Reflection.
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.
OOP Languages: Java vs C++
Comp 248 Introduction to Programming Chapter 4 - Defining Classes Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.
Introduction to Java Appendix A. Appendix A: Introduction to Java2 Chapter Objectives To understand the essentials of object-oriented programming in Java.
Database Systems Group Department for Mathematics and Computer Science Lars Hamann, Martin Gogolla, Mirco Kuhlmann OCL-based Runtime Monitoring of JVM.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
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.
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.
Lecture Set 11 Creating and Using Classes Part B – Class Features – Constructors, Methods, Fields, Properties, Shared Data.
Dale Roberts Object Oriented Programming using Java - Enumerations Dale Roberts, Lecturer Computer Science, IUPUI Department.
Java™ How to Program, 9/e Presented by: Dr. José M. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
Object Based Programming Chapter 8. 2 In This Chapter We will learn about classes Garbage Collection Data Abstraction and encapsulation.
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.
Run-Time Storage Organization Compiler Design Lecture (03/23/98) Computer Science Rensselaer Polytechnic.
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
11/28/2015B.Ramamurthy1 Object-Oriented Design and Java B.Ramamurthy.
Lecture 4 Generic programming Advanced Java Programming 1 dr hab. Szymon Grabowski dr inż. Wojciech Bieniecki
Chapter 4&5 Defining Classes Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
EE 422C Day 2 Java, Eclipse. Copyright Pearson Education, 2010 Based on slides bu Marty Stepp and Stuart Reges from
CS884 (Prasad)java11Extn1 Java 1.1 Extensions Nested classes static public/protected/private.
CSCE 314 Programming Languages Reflection Dr. Hyunyoung Lee 1.
Reflection Bibliografie: Sun: The Java Tutorials – The Reflection API IBM developerWorks:
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Inheritance and Class Hierarchies Chapter 3. Chapter Objectives  To understand inheritance and how it facilitates code reuse  To understand how Java.
Spring 2009 Programming Fundamentals I Java Programming XuanTung Hoang Lecture No. 8.
© 2006 Pearson Addison-Wesley. All rights reserved 1-1 Chapter 1 Review of Java Fundamentals.
Reflection Mehdi Einali Advanced Programming in Java 1.
CS 3180 (Prasad)L67Classes1 Classes and Interfaces Inheritance Polymorphism.
C# Fundamentals An Introduction. Before we begin How to get started writing C# – Quick tour of the dev. Environment – The current C# version is 5.0 –
METADATA IN.NET Presented By Sukumar Manduva. INTRODUCTION  What is Metadata ? Metadata is a binary information which contains the complete description.
Memory Management in Java Mr. Gerb Computer Science 4.
JAVA ACCESS MODIFIERS. Access Modifiers Access modifiers control which classes may use a feature. A classes features are: - The class itself - Its member.
SESSION 1 Introduction in Java. Objectives Introduce classes and objects Starting with Java Introduce JDK Writing a simple Java program Using comments.
Object Based Programming Chapter 8. 2 Contrast ____________________ Languages –Action oriented –Concentrate on writing ________________ –Data supports.
Sung-Dong Kim, Dept. of Computer Engineering, Hansung University Java - Introduction.
Modern Programming Tools And Techniques-I
Chapter 7: Cloning and RTTI
Reflection SoftUni Team Technical Trainers Java OOP Advanced
Objects as a programming concept
Introspection the process by which a builder tool finds out which properties, methods, and events a bean supports. searching for classes and methods that.
CSE 413, Autumn 2002 Programming Languages
Reflection SoftUni Team Technical Trainers C# OOP Advanced
Microsoft .NET 3. Language Innovations Pan Wuming 2017.
Java Review: Reference Types
Presentation on Object Oriented programming Topic
EE 422C Java Reflection re·flec·tion rəˈflekSH(ə)n/ noun
Object Based Programming
Advanced Programming in Java
CIS 199 Final Review.
Some Examples Reflection is used for many things:
CSCE 314: Programming Languages Dr. Dylan Shell
Presentation transcript:

Advanced Java Programming Lecture 5 Reflection dr hab. Szymon Grabowski dr inż. Wojciech Bieniecki References:

Reflection In Java: Provides a rich and advanced set of tools for writing programs which dynamically can manage Java code Is commonly used by programs which require the ability to examine or modify the runtime behavior of applications running in the JVM This mechanism is often used in JavaBeans Wikipedia: In computer science, reflection is the ability of a computer program to examine and modify the structure and behavior of an object at runtime - its values, meta-data, properties and functions. Reflection is most commonly used in high-level virtual machine programming languages, scripting languages but also statically typed programming languages Looking into the structure of the objects is called type introspection.

Reflection usage ● Analysis of class properties at application runtime ● Inspection of objects at application runtime. For example, to write a toString method that works in all classes ● Implementation of generic code which manipulates arrays ● The usage of Method objects that work like pointers to functions in C++

Reflection properties Reflection is an advanced feature and should be used only by developers who have a strong knowledge ofJava. With this in mind, reflection is a powerful technique and can enable applications to perform operations which would otherwise be impossible. Extensibility Features We may use external, user-defined classes by creating instances of extensibility objects using their fully-qualified names. Class Browsers and Visual Development Environments A class browser needs to be able to enumerate the members of classes. Visual development environments can benefit from making use of type information available in reflection to help the developer. Debuggers and Test Tools Debuggers need to be able to examine private members on classes. Test sequences may use reflection to systematically call a discoverable set of APIs defined on a class, to insure a high level of code coverage in a test suite.

How to obtain java.lang.Class object? All types in Java including the primitive types (int, float etc.) have an associated Class object. They can be obtained in a few ways: If an instance of an object is available, then by invoking object.getClass(): Class c = myObject.getClass(); If fully-qualified class name is available: Class c = Class.forName("com.bull.MyService"); If there is no instance, but the type is available: int test; Class c = test.getClass(); // compile-time errorClass c = test.class; // correct It should be noted that a Class object, in fact, refers to a type, which may or may not be a class. For example, an int is not a class, but int.class is an object of class Class

Basic operation on Class object JVM for every type, supports a unique Class object, therefore, to compare them operator == can be used if (e.getClass() == Test.class) Creates copies of the classes on the fly e.getClass().newInstance(); The most important functions of reflection mechanism, allowing the analysis of a class structure are located in three classes from java.lang.reflect Field Method Constructor

The use of reflection getType() Returns a Class object that identifies the declared type for the field represented by this Field object. getModifiers() Returns the Java language modifiers for the field represented by this Field 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. getReturnType() Returns a Class object that represents the formal return type of the method represented by this Method object. getModifiers() Returns the Java language modifiers for the constructor represented by this Constructor object, as an integer. getParameterTypes() Returns an array of Class objects that represent the formal parameter types, in declaration order, of the constructor represented by this Constructor object.

Example: a generic array code Available in java.lang.reflect, class Array, allows to dynamically create or expand tables. Students[] stud = new Students[100]; //We want to expand table stud = (Students[])moreArray(stud); //moreArray() is our method Implementation of moreArray(): static Object goodArrayGrow(Object stud) { Class my = stud.getClass(); if (!my.isArray()) return null; Class componentType = my.getComponentType(); int length = Array.getLength(a); int biggerSize=length+10; Object biggerArray = Array.newInstance(componentType, biggerSize); System.arraycopy(a, 0, biggerArray, 0, length); return biggerArray; }

Examining and modifying Enums Reflection provides three enum-specific APIs: Class.isEnum() Indicates whether this class represents an enum type Class.getEnumConstants() Retrieves the list of enum constants defined by the enum in the order they're declared java.lang.reflect.Field.isEnumConstant() Indicates whether this field represents an element of an enumerated type Fields which store enums are set and retrieved as any other reference type. field.set() public void set(Object obj,Object value); Sets the field represented by this Field object on the specified object argument to the specified new value. field.get(); Returns the value of the field represented by this Field, on the specified object.

Reflection drawbacks Reflection is powerful, but should not be used blindly. If it is possible to perform an operation without using reflection, then avoid it. Performance Overhead Reflection involves types that are dynamically resolved, some JVM optimizations can not be performed. Consequently, reflective operations are much slower and should be avoided in loops. Security Restrictions Reflection requires a runtime permission which is not available under a security manager in a restricted security context (especially applets). Exposure of Internals Reflection allows to make operations that are illegal in non-reflective code (accessing private fields and methods). It can result in unexpected side-effects. Reflective code breaks abstractions and therefore may change behavior with upgrades of the platform.