Reflection API Faculty of Information Technologies Industrial University of Ho Chi Minh City Java Programming Course 1.

Slides:



Advertisements
Similar presentations
Introduction to Java Reflection
Advertisements

Chapter 1 Object-Oriented Concepts. A class consists of variables called fields together with functions called methods that act on those fields.
Reflection Reflection is the ability of a program to examine and modify the structure and behavior of an object at runtime.
METHOD OVERRIDING 1.Sub class can override the methods defined by the super class. 2.Overridden Methods in the sub classes should have same name, same.
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.
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.
CS2200 Software Development Lecture: Object class A. O’Riordan, 2008.
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.
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.
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.
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.
CSC3170 Introduction to Database Systems
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.
Advanced Java Programming Lecture 5 Reflection dr hab. Szymon Grabowski dr inż. Wojciech Bieniecki
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.
1 Object-Oriented Software Engineering CS Interfaces Interfaces are contracts Contracts between software groups Defines how software interacts with.
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.
2000 Jordan Anastasiade. All rights reserved. 1 Class In this lesson you will be learning about: Class. Inheritance. Polymorphism. Nested and.
Basic Java Syntax CSE301 University of Sunderland Harry R Erwin, PhD.
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.
Chap. 1 Classes, Types, and Objects. How Classes Are Declared [ ] class [extends ] [implements,, … ] { // class methods and instance variable definitions.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Reflection in Java Bibliografie: Sun: The Java Tutorials – The Reflection API Java programming.
Page: 1 การโปรแกรมเชิงวัตถุด้วยภาษา JAVA บุรินทร์ รุจจนพันธุ์.. ปรับปรุง 15 มิถุนายน 2552 Keyword & Data Type มหาวิทยาลัยเนชั่น.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Chapter 5 Objects and Classes Inheritance. Solution Assignments 3 & 4 Review in class…..
CS884 (Prasad)java11Extn1 Java 1.1 Extensions Nested classes static public/protected/private.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
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,
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.
Classes, Interfaces and Packages
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.”
Topics Instance variables, set and get methods Encapsulation
CSC 243 – Java Programming, Spring, 2014 Week 4, Interfaces, Derived Classes, and Abstract Classes.
Object-Oriented Concepts
Chapter 7: Cloning and RTTI
NESTED CLASSES REFLECTION PROXIES.
JAVA MULTIPLE CHOICE QUESTION.
Java Programming Course
Java Primer 1: Types, Classes and Operators
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.
Overloading and Constructors
Java Programming Language
The Building Blocks Classes: Java class library, over 1,800 classes:
Môn: Lập trình Hướng đối tượng (Object Oriented Programming)
1. Các khái niệm trong PTTK HĐT (tt)
Programs and Classes A program is made up from classes
Java Programming Language
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:

Reflection API Faculty of Information Technologies Industrial University of Ho Chi Minh City Java Programming Course 1

Session objectives 1. Introduction 2. The Class object 1. Getting Constructors 2. Getting Fields 3. Getting Methods 4. Array Object 3. Invoke methods dynamically 2

Java looking at Java One of the unusual capabilities of Java is that a program can examine itself o You can determine the class of an object o You can find out all about a class: its access modifiers, superclass, fields, constructors, and methods o You can find out what what is in an interface o Even if you don ’ t know the names of things when you write the program, you can: Create an instance of a class Get and set instance variables Invoke a method on an object Create and manipulate arrays 3

What is reflection for? In “ normal ” programs you don ’ t need reflection You do need reflection if you are working with programs that process programs Typical examples: o A class browser o A debugger o A GUI builder o An IDE, such as BlueJ, Netbeans oe eclipse o A program to grade student programs 4

Reflection Reflection là kĩ thu ậ t r ấ t c ầ n thi ế t đ ể l ấ y các thông tin c ủ a m ộ t ki ể u d ữ li ệ u. D ự a vào đó ta có th ể kích ho ạ t (nh ư các ph ươ ng th ứ c) ho ặ c t ạ o th ể hi ệ n c ủ a ki ể u d ữ li ệ u đó 5

Ki ế n trúc c ủ a Java Reflection API Các l ớ p đ ượ c dùng trong reflection n ằ m trong hai package là java.lang và java.lang.reflect.java.lang.reflect Package java.lang.reflect bao g ồ m ba l ớ p chính c ầ n bi ế t là Constructor, Field và Method 6

Ki ế n trúc c ủ a Java Reflection API Class : l ớ p này đ ạ i di ệ n cho các l ớ p, interface và ch ứ a các ph ươ ng th ứ c dùng đ ể l ấ y các đ ố i t ượ ng ki ể u Constructor, Field, Method,… Class : AccessibleObject: các ki ể m tra v ề ph ạ m vi truy xu ấ t (public, private, protected) c ủ a field, method, constructor s ẽ đ ượ c b ỏ qua. Constructor: ch ứ a các thông tin v ề m ộ t constructor c ủ a l ớ p. AccessibleObject Constructor Field: ch ứ a các thông tin v ề m ộ t field c ủ a l ớ p, interface. Field Method: ch ứ a các thông tin v ề m ộ t ph ươ ng th ứ c c ủ a l ớ p, interface. Method 7

T ạ o đ ố i t ượ ng Class<> Đ ố i t ượ ng ki ể u này đ ượ c t ạ o ra b ằ ng cách s ử d ụ ng ph ươ ng th ứ c static Class.forName(): Class cls = Class.forName("demo.NhanVien"); ==> ClassNotFoundException Class cls = demo.NhanVien.class; 8

The Class class To find out about a class, first get its Class object o If you have an object obj, you can get its class object with Class c = obj.getClass(); o You can get the class object for the superclass of a Class c with Class sup = c.getSuperclass(); o If you know the name of a class (say, Button ) at compile time, you can get its class object with Class c = Button.class; o 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); 9

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 10

Getting all the superclasses getSuperclass() returns a Class object (or null if you call it on Object, which has no superclass) Example 11

Getting the class modifiers I The modifiers (e.g., public, final, abstract etc.) of a Class object is encoded in an int and can be queried by the method getModifiers(). To decode the int result, we need methods of the Modifier class, which is in java.lang.reflect, so: import java.lang.reflect.*; Then we can do things like: if (Modifier.isPublic(m)) System.out.println("public"); Or String modifier= Modifier.toString(cls.getModifiers()) System.out.println(modifier); 12

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

Getting interfaces A class can implement zero or more interfaces getInterfaces() returns an array of Class objects Ex: 14

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: o getModifiers() o getFields() // "fields" == "instance variables" o getConstructors() o getMethods() o isArray() 15

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

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

Using Field s (2) The fields of a particular object obj may be accessed with: o 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 o Object f.get(obj) returns the value of the field, assuming it is an Object o 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 18

Getting Constructors of a class if c is a Class, then c.getConstructors() : Constructor[] return an array of all public constructors of class c. c.getConstructor( Class … paramTypes ) returns a constructor whose parameter types match those given paramTypes. Ex: String.class.getConstructors().length > 15; String.class.getConstructor( char[].class, int.class, int.class).toString() > String(char[], int,int). 19

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

Example Constructor c = String.class.getConstrucor( char[].class, int.class, int.class).toString()  String(char[], int,int). String s = c.newInstance( new char[] {‘a’,’b’,’c’,’d’ }, 1, 2 ); assert s == “bc”; 21

Example 22

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

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

Methods 25

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

Examples of invoke() “abcdefg”.length() > 7 Method lengthMethod = String.class.getMethod(“length”) ; lengthMethod.invoke(“abcdefg”) > 7 “abcdefg”.substring(2, 5) > cde Method substringMethod = String.class.getMethod ( “substring”, int.class, Integer.TYPE ) ; substringEMthod.invoke( “abcdefg”, 2, new Integer(5) ) > cde 27

Examples of invoke() 28

Arrays I To determine whether an object obj is an array, o Get its class c with Class c = obj.getClass(); o Test with c.isArray() To find the type of components of the array, o c.getComponentType() Returns null if c is not the class of an array Ex: o int[].class.isArray() == true ; o int[].class.getComponentType() == int.class 29

Arrays II The Array class in java.lang.reflect provides static methods for working with arrays To create an array, Array.newInstance(Class componentType, int size) o This returns, as an Object, the newly created array You can cast it to the desired type if you like o The componentType may itself be an array This would create a multiple-dimensioned array The limit on the number of dimensions is usually 255 Array.newInstance(Class componentType, int… sizes) o This returns, as an Object, the newly created multidimensional array (with sizes.length dimensions) 30

Examples The following two objects are of the same type: o new String[10] o Array.newInstance(String.class, 10) The following two objects are of the same type: o new String[10][20] o Array.newInstance(String.class, 10, 20) 31

Arrays III To get the value of array elements, o Array.get(Object array, int index) returns an Object o Array.getBoolean(Object array, int index) returns a boolean o Array.getByte(Object array, int index) returns a byte o etc. To store values into an array, o Array.set(Object array, int index, Object value) o Array.setInt(Object array, int index, int i) o Array.setFloat(Object array, int index, float f) o etc. 32

Examples a = new int[] {1,2,3,4}; Array.getInt(a, 2) //  3 Array.setInt(a, 3, 5 ) // a = {1,2,3, 5 }. s = new String[] { “ab”, “bc”, “cd” }; Array.get(s, 1 ) //  “bc” Array.set(s, 1, “xxx”) // s[1] = “xxx” 33

Array example 34 Output

Getting non-public members of a class All getXXX() methods of Class mentioned above return only public members of the target (as well as ancestor ) classes, but they cannot return non-public members. There are another set of getDeclaredXXX() methods in Class that will return all (even private or static ) members of target class but no inherited members are included. getDeclaredConstructors(), defDeclaredConstrucor(Class…) getDeclaredFields(), getDeclaredField(String) getDeclaredmethods(), getDeclaredMethod(String, Class…) 35

Example String.class.getConstructors().length > 15 String.class.getDeclaredConstructors().length > 16. Constructor[] cs = String.class.getDeclaredConstructors(); for(Constructor c : cs) if( ! (Modifier.isPublic(c.getModifiers()))) out.println(c); > java.lang.String(int,int,char[]) // package 36

Create object at runtime Example class 37

Create object dynamically 38

Call method dynamically 39

ClassLoader Dùng URI đ ể đ ọ c n ộ i dung class lên 1 m ả ng bytes Subclassing l ớ p ClassLoader đ ể t ạ o đ ố i t ượ ng Class X ử lý 40

Concluding comments Many of these methods throw exceptions not described here o For details, see the Java API Reflection isn ’ t used in “ normal ” programs, but when you need it, it ’ s indispensable Studying the java reflection package gives you a chance to review the basics of java class structure. 41

42 FAQ

That’s all for this session! Thank you all for your attention and patient ! 43/27 43