Reflection Mehdi Einali Advanced Programming in Java 1.

Slides:



Advertisements
Similar presentations
Sadegh Aliakbary Sharif University of Technology Spring 2011.
Advertisements

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.
ITEC200 – Week03 Inheritance and Class Hierarchies.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Inheritance and Polymorphism.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Fall 2007CS 2251 Inheritance and Class Hierarchies Chapter 3.
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.
Terms and Rules Professor Evan Korth New York University (All rights reserved)
1 Inheritance and Polymorphism. 2 Motivations Suppose you will define classes to model circles, rectangles, and triangles. These classes have many common.
1 Java object model Part 3: Serialization & Reflection.
Appendix A.2: Review of Java and Object-Oriented Programming: Part 2 “For the object-oriented project, remember that the primary unit of decomposition.
Sadegh Aliakbary. Copyright ©2014 JAVACUP.IRJAVACUP.IR All rights reserved. Redistribution of JAVACUP contents is not prohibited if JAVACUP.
Programming Languages and Paradigms Object-Oriented Programming.
1 Inheritance and Polymorphism Chapter 9. 2 Polymorphism, Dynamic Binding and Generic Programming public class Test { public static void main(String[]
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 11 Inheritance and Polymorphism.
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.
Object Oriented Programming in Java Lecture 13. Java Reflection Reflection is a feature unique to Java that allows an executing program to examine or.
Introduction to Java Prepared by: Ahmed Hefny. Outline Classes Access Levels Member Initialization Inheritance and Polymorphism Interfaces Inner Classes.
Predefined Classes in Java Ellen Walker CPSC 201 Data Structures Hiram College.
The Reflection Lucielle Mendez Antonio Bologna.
Programming Languages and Paradigms Object-Oriented Programming (Part II)
Course contents Basic concepts –What is software architecture ? Fundamental architectural styles –Pipes and filters –Layers –Blackboard –Event-driven Architectural.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 11 Inheritance and Polymorphism.
Inheritance and Polymorphism Daniel Liang, Introduction to Java Programming.
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.
1 Generics Chapter 21 Liang, Introduction to 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.
Programming in Java CSCI-2220 Object Oriented Programming.
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.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 10 Inheritance and.
Chapter 4 Generic Vector Class. Agenda A systemic problem with Vector of Object – Several approaches at a solution – Generic structures Converting classes.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
More on Objects Mehdi Einali Advanced Programming in Java 1.
Sadegh Aliakbary. Copyright ©2014 JAVACUP.IRJAVACUP.IR All rights reserved. Redistribution of JAVACUP contents is not prohibited if JAVACUP.
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.
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.
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
Inheritance ndex.html ndex.htmland “Java.
CS 112 Programming 2 Lecture 06 Inheritance & Polymorphism (1)
Topics Instance variables, set and get methods Encapsulation
Lecture 5:Interfaces and Abstract Classes Michael Hsu CSULA.
BY:- TOPS Technologies
OOP Tirgul 10. What We’ll Be Seeing Today  Generics – A Reminder  Type Safety  Bounded Type Parameters  Generic Methods  Generics and Inner Classes.
Objects and Memory Mehdi Einali Advanced Programming in Java 1.
Sadegh Aliakbary Sharif University of Technology Fall 2010.
Modern Programming Tools And Techniques-I
Chapter 7: Cloning and RTTI
NESTED CLASSES REFLECTION PROXIES.
Chapter 11 Inheritance and Polymorphism
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
Advanced Programming in Java
EE 422C Java Reflection re·flec·tion rəˈflekSH(ə)n/ noun
CS 302 Week 11 Jim Williams, PhD.
Advanced Programming in Java
Chapter 9 Inheritance and Polymorphism
Advanced Programming Behnam Hatami Fall 2017.
Advanced Programming in Java
Advanced Programming in Java
Chapter 11 Inheritance and Polymorphism Part 2
CSCE 314: Programming Languages Dr. Dylan Shell
Presentation transcript:

Reflection Mehdi Einali Advanced Programming in Java 1

2 Agenda What is RTTI? Why we need it? Type information Java and Reflection

3 A Challenge Suppose you want to implement general remote code runner What do you need? Socket Programming Serialization How do you invoke methods in other side?

4 Problem Suppose you should write a program It reads the name of a class And the name of one of its methods And all of its parameters The program creates and object from the specified class and invokes the specified method with specified parameters

5 Problem (2) How can you implement it? What is its application? RPC and RMI Object transfer to a web service

6 RTTI Runtime type information (RTTI) Allows you to discover and use type information while a program is running This feature is also called Reflection in java

7 RTTI (2) With RTTI, you can ask an object reference the exact type that it’s referring to. And you can get information about it its characteristics and capabilities Methods, constructors, fields, … And you can call its methods and get its properties

8 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

9 The Class Object How type information is represented at run time? This is accomplished through a special kind of object It is called the Class object it contains information about the class Java performs its RTTI using the Class object

10 Class Loader There’s one Class object for each class that is part of your program Each time you write and compile a new class, a single Class object is also created and stored, appropriately enough, in an identically named.class file To make an object of that class, JVM uses a subsystem called a class loader

11 How Classes are Loaded? A classes is loaded into the JVM dynamically upon the first use of the class When? when the program makes the first reference to a static member of that class The constructor is also a static method of a class! Even though the static keyword is not declared Instantiation: using the new operator  a reference to a static member (constructor)

12 Dynamic Loading A Java program isn’t completely loaded before it begins Pieces of it are loaded when necessary This is called Dynamic loading Different from many traditional languages Enables difficult or impossible behavior to duplicate in a statically loaded language like C++.

13 Default Class Loader The class loader first checks: Is the Class object for that type loaded? If not, class loader finds the.class file and loads it A customized class loader may load the class from a DB

14 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.

15 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.

16 First Example Method method = String.class.getMethod( "substring", int.class); Object value = method.invoke("Taghi Taghavi", 6); System.out.println((String)value);

17 Example Class c = Class.forName(args[0]); Method m[] = c.getDeclaredMethods(); for (int i = 0; i < m.length; i++) System.out.println(m[i].toString( ));

18 More Reflection Class clazz = object.getClass(); Annotation[] annotations = clazz.getAnnotations(); Field[] fields = clazz.getFields(); Constructor[] constructors = clazz.getConstructors();

19 Example package drawing; class MyClass{ String name; public MyClass(String name) { this.name = name; } public String getName() { return name; }

20 Example (contd.) Class c = Class.forName("drawing.MyClass"); Constructor constructor = c.getConstructor(String.class); MyClass instance = (MyClass) constructor.newInstance("Ali Alavi"); Field field = instance.getClass().getDeclaredField("name"); field.set(instance, "Taghi Taghavi"); System.out.println(instance.getName());

21 instanceof Operator Tells you if an object is an instance of a particular type if(x instanceof Dog) ((Dog)x).bark(); Use instanceof before a downcast when you don’t have other information that tells you the type of the object; Otherwise, you may end up with a …? ClassCastException

22 instanceof void f(Object c){ if(c instanceof Serializable && c instanceof String) System.out.println("YES!"); } instanceof returns false if the reference is null

23 instanceof vs. Class equivalence There’s an important difference between instanceof and the direct comparison of the Class objects But instanceof and islnstance() produce equivalent results if(c instanceof String)... if(c.getClass().equals(String.class))...

24 question

25 How to Retrieve Class Object Compile time code (Hard coded) 1. ClassName.class Class clazz = Person.class; Runtime 2. Class.forName Class clazz = Class.forName("edu.sharif.ce.Rectangle"); 3. reference.getClass Object o = new Person(); Class clazz= o.getClass();

26 Class is a Generic Class Example1 Class clazz = Person.class; Person p = clazz.newInstance(); No cast is needed Example2 Object o = new Person(); Class c = o.getClass();

27 Class and Generic Types What is wrong with this code? class GenericType { private T element; public void f(){ Class c2 = element.getClass(); Class c1 = T.class; } No generic type information at runtime Remember erasure

28 TYPE in Wrapper Classes

29 Changing the Accessibility! class MyClass{ private void privateMethod(){ }... MyClass instance = new MyClass(); Method method = instance.getClass(). getDeclaredMethod("privateMethod"); method.setAccessible(true); method.invoke(instance);

30 Swap two integers public static void swap(Integer i, Integer j) { try { Integer lastJ = new Integer(j); Field value = Integer.class.getDeclaredField("value"); value.setAccessible(true); value.set(j, i); value.set(i, lastJ); value.setAccessible(false); } catch (Exception e) { e.printStackTrace(); } OO cries on this capability

31 Happy programming