SlideShare a Scribd company logo
1 of 41
Advanced Java ProgrammingLecture-02: Reflection Aatif Kamal,   Dept. of Computing Aatif.kamal@seecs.edu.pk Study Source: http://download.oracle.com/javase/tutorial/reflect/
Reflection Overview Reflection API The “Class" class Class methods Array class Member interface Method class invoking a method, throwing exceptions Field class accessible objects
Background Programs are just another kind of data Source code is text Manipulate it line by line, or by parsing expressions Compiled programs are data, too Integers and strings are bytes in memory that you interpret a certain way Instructions in methods are just bytes too No reason why a program can't inspect itself
How objects work Every object is either a reference or primitive type. object class Point {   public Point(int x, int y) {    }   public getX() {}   public getY() {}   protected int x, y; } 5 x 3 y class {…} Point(int,int) {…} getX() {…} getY()
5 Defining Reflection Introduced in Java 1.1. Called the "Java Core Reflection API" Reflection is commonly used by programs which require the ability to examine or modify the runtime behavior of applications running in the Java virtual machine Allows you to find out information about any object, including its methods and fields, at run time. Can no longer get away with this called an enabling technology because it supports Java language elements such as: Java Beans, Serialization, and Remote Method Invocation (RMI). JBoss, Tomcat, Eclipse, etc. are reflection-based
6 Reflection Can be Used To . . . construct new class instances and new arrays  access and modify fields of objects and classes  invoke methods on objects and classes  access and modify elements of arrays
Uses of Reflection Extensibility Features  An application may make use of 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 aid the developer in writing correct code.  Debuggers and Test Tools  Debuggers need to be able to examine private members on classes. Test harnesses can make use of reflection to systematically call a discoverable set APIs defined on a class, to insure a high level of code coverage in a test suite.
Drawbacks of Reflection Reflection is powerful, but should not be used indiscriminately.  If it is possible to perform an operation without using reflection, then it is preferable to avoid using it. Performance Overhead Because reflection involves types that are dynamically resolved, certain Java virtual machine optimizations can not be performed.  Slower performance than their non-reflective counterparts, should be avoided in sections of code which are called frequently in performance-sensitive applications.  Security Restrictions Reflection requires a runtime permission which may not be present when running under a security manager.   Code which has to run in a restricted security context, such as in an Applet.
Drawbacks of Reflection Exposure of Internals Since reflection allows code to perform operations that would be illegal in non-reflective code,  Accessing private fields and methods, the use of reflection can result in unexpected side-effects, Reflective code breaks abstractions and therefore may change behavior with upgrades of the platform.
Class  c = Class.forName(“java.lang.String”); Object o = c.newInstance(); Reflection - Classes Reflection is a dynamic language feature Used to query object and class information static Class Class.forName(String className) Obtain a java.lang.Class object i.e. Class.forName(“java.lang.String”) gets an object corresponding to class String Object Class.newInstance() Object constructor in disguise Create  a new object of a given class This makes a new empty string.
Running Example Most typical use of reflection: Take a class name, make a Class object Create object of that class, cast and use it Statically convert Class.newInstancenew T() 1. String className = ...; 2. Class  c = Class.forName(className); 3. Object o = c.newInstance(); 4. T t      = (T) o;		 new T1(); new T2(); ...
12 Reflection API Package java.lang.reflect Field class get name and access for an arbitrary field Method class get info about an arbitrary method (and invoke it) Constructor class get info about an arbitrary constructor (and invoke it) Classclass creates new instances of Field, Method, and Constructor Array class static methods to create and get info about arbitrary arrays ….. With the exception of java.lang.reflect.ReflectPermission, none of the classes in java.lang.reflect have public constructors.
java.lang.Class For every type of object, the Java virtual machine instantiates an immutable instance of java.lang.Class Class objects represent a loaded class Provides methods to examine the runtime properties of the object  its methods its fields its superclass the interfaces it implements whether it's an array Provides the ability to create new classes and objects.  Entry point for all of the Reflection APIs
14 Obtaining a Class Object To get to these classes, it is necessary to invoke appropriate methods on Class. At compile time, using the symbolic class name: Class c1 = String.class; Class c2 = Employee[].class; At runtime, by calling getClass( ) on any object: Class c3 = obj.getClass( ); At runtime, by passing a class name (string) to the forName( ) static method: Class c = Class.forName( "java.util.Date" );
Retrieving Class Objects - Examples Object.getClass() the simplest way to get its Class is to invoke Object.getClass() Class c = "foo".getClass();    Returns the Class for String Class c = System.console().getClass();  the Class corresponding to java.io.Console.  enum E { A, B }; 	Class c = A.getClass(); A is is an instance of the enum E; thus getClass() returns   		the Class corresponding to the enumeration type E. byte[] bytes = new byte[1024]; 	Class c = bytes.getClass(); Since arrays are Objects, it is also possible to invoke 		getClass() on an instance of an array. The returned Class 		corresponds to an array with component type byte.
Retrieving Class Objects - Examples The .class Syntax If the type is available but there is no instance then it is possible to obtain a Class by appending ".class" to the name of the type. This is also the easiest way to obtain the Class for a primitive type.  boolean b; Class c = b.getClass();  	    // compile-time error Class c = boolean.class;               // correct  Class c = java.io.PrintStream.class;  Class c = int[ ][ ][ ].class;
Retrieving Class Objects - Examples Class.forName() If the fully-qualified name of a class is available, it is possible to get the corresponding Class using the static method Class.forName() Class driverObject = Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver");  Class c = Class.forName("com.duke.MyLocaleServiceProvider") TYPE Field for Primitive Type Wrappers Two ways  .class syntax, more convenient and the preferred way Class c = boolean.class;Class c1 = String.class;Class c2 = Employee[].class; All primitive types & void has a wrapper class in java.lang, used for boxing of primitive types to reference types.  Each wrapper class contains a field named TYPE which is equal to the Class for the primitive type being wrapped. Class c = Double.TYPE;
18 Class Methods(1 of 4) public String getName( ); Returns the name of the class referred to by the Class object. public booleanisInterface( ); Returns true if the Class object refers to an interface. public booleanisArray( ); Returns true if the Class object refers to an array type. public Class getSuperclass( ); Returns the superclass of the current Class object.
19 Class Methods (2 of 4) public Class[] getInterfaces( ); Returns array of interface classes implemented by this class. public Class[] getClasses( ); Returns array of inner classes within this class. public Object newInstance( ); Creates and returns an instance of this class. public static Class forName( String name ); Returns a Class object corresponding to a class name (static method)
20 Class Methods (3 of 4) public Constructor[] getConstructors( ); Returns an array of all public constructors in the current class. 	(import java.lang.reflect.Constructor) public Method[] getDeclaredMethods( ); Returns an array of all public and private methods declared in the current class or interface. 	(import java.lang.reflect.Method) public Method[] getMethods( ); Returns an array of all public methods in the current class, as well as those in all superclasses and superinterfaces.
Code Examples  ReflectMethod.java & ReflectMethod2.java  Class, Parent Class, Package name Show all methods name, signatures – use getMethods() Bypassing Abstraction  SpecificMethodInfoDemo.java Showing method directly using getMethod() Bridge method Concept SampleInvoke .java,RunMethod.java & InovkeMain.java How to execute a method – using Method.invoke() Recursion through Reflection PrivateMethod.java Executing private methods of a class
22 Member Interface Implemented by Constructor, Method, and Field Class getDeclaringClass( )  returns the Class object representing the class or interface that declares the member or constructor represented by this Member.  intgetModifiers( )  returns the Java language modifiers for the member or constructor represented by this Member, as an integer.  String getName( )  returns the simple name of the underlying member or constructor represented by this Member.
23 Using a Method Object Using a Method object, you can... get its name and parameter list and invoke the method Obtain a Method from a signature, or get a list of all methods. To specify the signature, create an array of Class objects representing the method’s parameter types. Array will be zero-length if no parameters Special Class objects for primitives
24 Representing the Primitive Types Special Class objects representing the eight primitive types: Byte.TYPE, Character.TYPE, Integer.TYPE, Long.TYPE, Short.TYPE, Double.TYPE, Float.TYPE, Boolean.TYPE Void Class type:  Void.TYPE Also Class types for arrays, such as ... class type for int[ ] is Integer.TYPE[].class class type for int[ ][ ] is Integer.TYPE[][].class
25 Method Class public class Method implements Member { public Class getReturnType( ); public Class[] getParameterTypes( ); public String getName( ); public intgetModifiers( ); public Class[] getExceptionTypes( ); public Object invoke( Object obj, Object[] args); } The modifiers are stored as a bit pattern; class Modifier has methods to interpret the bits.
26 Method Examples Retrieve the name of a method: Method meth = c1.getDeclaredMethods( ); String name = meth.getName( ); Retrieve an array of parameter types: Class parms[] = meth.getParameterTypes( ); Retrieve a method's return type: Class retType = meth.getReturnType( );
27 Method.invoke( ) public Object invoke(Object obj, Object[] args) If the parameters or return types are primitives, they are wrapped using one of the eight wrapper classes. example: Integer.TYPE The first parameter to invoke is the controlling object  (use null for static methods) The second parameter is the parameter list array of objects Disadvantages to using invoke( ): executes more slowly than static invocation you have to handle all checked exceptions you lose lots of compile-time checks
28 Exceptions and Invoke( ) If invoked method throws an exception, invoke( ) will throw an InvocationTargetException get the actual exception by calling getException Lots of other exceptions to worry about before you call invoke: Did class load? ClassNotFoundException Was method found? NoSuchMethodException Can you access method? IllegalAccessException
29 Example: Invoking main( ) Calling: main( String[] args ) Simplified, with no error checking: Class cl = Class.forName( className ); Class[] paramTypes = new Class[] { String[].class }; Method m = cl.getDeclaredMethod( "main", paramTypes ); Object[] args = new Object[] 	{ new String[] { "Breathing", "Fire" } } m.invoke( null, args );
30 Invoking a Constructor Call getConstructor( ),  	then call newInstance( ) catch InstantiationException Class c1 = Class.forName("Villain"); Class[] paramTypes = new Class[] {String.class,Integer.TYPE }; Constructor m = c1.getConstructor( paramTypes );		 Object[] arguments = new Object[] { "Darth Vader", 				new Integer(20) }; Villan v = (Villan) m.newInstance(arguments);
31 Member Interface Implemented by Constructor, Method, and Field Class getDeclaringClass( )  returns the Class object representing the class or interface that declares the member or constructor represented by this Member.  intgetModifiers( )  returns the Java language modifiers for the member or constructor represented by this Member, as an integer.  String getName( )  returns the simple name of the underlying member or constructor represented by this Member.
Code Examples  ReflectMethod.java & ReflectMethod2.java  Class, Parent Class, Package name Show all methods name, signatures – use getMethods() Bypassing Abstraction  SpecificMethodInfoDemo.java Showing method directly using getMethod() Bridge method Concept SampleInvoke .java,RunMethod.java & InovkeMain.java How to execute a method – using Method.invoke() Recursion through Reflection PrivateMethod.java Executing private methods of a class
33 The Array Class import java.lang.reflect.Array; public class Array { // all static methods: public int getLength( Object arr ); public Object newInstance( Class elements, int length ); public Object get( Object arr, int index ); public void set( Object arr, int index, Object val ); // Various specialized versions, such as... public int getInt( Object arr, int index ); public void setInt( Object arr, int index, int val ); }
34 Array Samples Canine[] kennel = new Canine[10]; . int n = Array.getLength( kennel ); // set the contents of an array element Array.set( kennel, (n-1), new Canine( "Spaniel" ) ); // get an object from the array, determine its class, // and display its value: Object obj = Array.get( kennel, (n-1) ); Class c1 = obj.getClass( );		 System.out.println( c1.getName( )  	+ "-->"  	+ obj.toString( ) );
35 Two Ways to Declare an Array // first: Canine kennel = new Canine[10]; // second: Class c1 = Class.forName( "Canine" ); Canine kennel = (Canine[]) Array.newInstance( c1, 10 ); next: expanding an Array
36 Example: Expanding an Array Problem statement: write a function that receives an arbitrary array, allocates storage for twice the size of the array, copies the data to the new array, and returns the new array
37 Example: Expanding an Array Why won't this code work? public static Object[] doubleArrayBad( Object[] arr ) { intnewSize = arr.length * 2 + 1; 	Object[] newArray = new Object[ newSize ]; 	for( inti = 0; i < arr.length; i++ ) newArray[ i ] = arr[ i ]; 	return newArray; }
38 Example: Expanding an Array Ans: This method always returns an array of Object, rather than the type of the array being copied. public static Object[] doubleArrayBad( Object[] arr ) { intnewSize = arr.length * 2 + 1; 	Object[] newArray = new Object[ newSize ]; 	for( inti = 0; i < arr.length; i++ ) newArray[ i ] = arr[ i ]; 	return newArray; }
39 Example: Expanding an Array Use reflection to get the array type: public Object[] doubleArray( Object[] arr ) { 	Class c1 = arr.getClass( );		 	if( !c1.isArray( ) ) return null; intoldSize = Array.getLength( arr ); intnewSize = oldSize * 2 + 1; 	Object[] newArray = (Object[]) Array.newInstance( 		c1.getComponentType( ), newSize ); 	for( inti = 0; i < arr.length; i++ ) newArray[ i ] = arr[ i ]; 	return newArray; } see ReflectionArrayTestjava
Assignment 02 Extension One to Assignment 01 Send a class object from one machine to another machine  On recipient side through reflection show complete description of object  Class, Parent class, Package, interface implemented  Class Properties,  their access modifier,  datatype, name & value Class methods, list all methods, access modifiers,  static/non static,  return Type, Name of method, Input parameters, exceptions  And execute any static method object on the recipient side.   Save this assignment code as different version.
Next Lecture  Java Logging - Log4J

More Related Content

What's hot (17)

Java tutorial for Beginners and Entry Level
Java tutorial for Beginners and Entry LevelJava tutorial for Beginners and Entry Level
Java tutorial for Beginners and Entry Level
 
Core java concepts
Core java  conceptsCore java  concepts
Core java concepts
 
Packages and inbuilt classes of java
Packages and inbuilt classes of javaPackages and inbuilt classes of java
Packages and inbuilt classes of java
 
Java Basics
Java BasicsJava Basics
Java Basics
 
Java tutorials
Java tutorialsJava tutorials
Java tutorials
 
Java Tutorial
Java TutorialJava Tutorial
Java Tutorial
 
Java Programming - 04 object oriented in java
Java Programming - 04 object oriented in javaJava Programming - 04 object oriented in java
Java Programming - 04 object oriented in java
 
Java basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini indiaJava basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini india
 
Core java Essentials
Core java EssentialsCore java Essentials
Core java Essentials
 
Core java
Core javaCore java
Core java
 
JAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examplesJAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examples
 
Basics of Java
Basics of JavaBasics of Java
Basics of Java
 
Core java complete ppt(note)
Core java  complete  ppt(note)Core java  complete  ppt(note)
Core java complete ppt(note)
 
Synapseindia reviews.odp.
Synapseindia reviews.odp.Synapseindia reviews.odp.
Synapseindia reviews.odp.
 
Access modifiers
Access modifiersAccess modifiers
Access modifiers
 
Core java notes with examples
Core java notes with examplesCore java notes with examples
Core java notes with examples
 
Access modifiers in java
Access modifiers in javaAccess modifiers in java
Access modifiers in java
 

Viewers also liked

Viewers also liked (7)

Java Programming
Java ProgrammingJava Programming
Java Programming
 
Simple Java Programs
Simple Java ProgramsSimple Java Programs
Simple Java Programs
 
Graphics programming in Java
Graphics programming in JavaGraphics programming in Java
Graphics programming in Java
 
Presentation on Core java
Presentation on Core javaPresentation on Core java
Presentation on Core java
 
Presentation on java
Presentation  on  javaPresentation  on  java
Presentation on java
 
Core java slides
Core java slidesCore java slides
Core java slides
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
 

Similar to Java Reflection Concept and Working

Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sirAdvanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sirAVINASH KUMAR
 
Advance java kvr -satya
Advance java  kvr -satyaAdvance java  kvr -satya
Advance java kvr -satyaSatya Johnny
 
packages and interfaces
packages and interfacespackages and interfaces
packages and interfacesmadhavi patil
 
Chap-2 Classes & Methods.pptx
Chap-2 Classes & Methods.pptxChap-2 Classes & Methods.pptx
Chap-2 Classes & Methods.pptxchetanpatilcp783
 
Cuối cùng cũng đã chuẩn bị slide xong cho seminar ngày mai. Mai seminar đầu t...
Cuối cùng cũng đã chuẩn bị slide xong cho seminar ngày mai. Mai seminar đầu t...Cuối cùng cũng đã chuẩn bị slide xong cho seminar ngày mai. Mai seminar đầu t...
Cuối cùng cũng đã chuẩn bị slide xong cho seminar ngày mai. Mai seminar đầu t...Khoa Nguyen
 
oops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaoops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaCPD INDIA
 
03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slotsmha4
 
03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slotsmha4
 
object oriented programming using java, second sem BCA,UoM
object oriented programming using java, second sem BCA,UoMobject oriented programming using java, second sem BCA,UoM
object oriented programming using java, second sem BCA,UoMambikavenkatesh2
 
C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorialsakreyi
 

Similar to Java Reflection Concept and Working (20)

Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sirAdvanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sir
 
Java Reflection
Java ReflectionJava Reflection
Java Reflection
 
Advance java kvr -satya
Advance java  kvr -satyaAdvance java  kvr -satya
Advance java kvr -satya
 
Adv kvr -satya
Adv  kvr -satyaAdv  kvr -satya
Adv kvr -satya
 
19 reflection
19   reflection19   reflection
19 reflection
 
packages and interfaces
packages and interfacespackages and interfaces
packages and interfaces
 
Chap-2 Classes & Methods.pptx
Chap-2 Classes & Methods.pptxChap-2 Classes & Methods.pptx
Chap-2 Classes & Methods.pptx
 
Java Reflection
Java ReflectionJava Reflection
Java Reflection
 
Sonu wiziq
Sonu wiziqSonu wiziq
Sonu wiziq
 
Lecture 2 classes i
Lecture 2 classes iLecture 2 classes i
Lecture 2 classes i
 
C# classes objects
C#  classes objectsC#  classes objects
C# classes objects
 
Ch-2ppt.pptx
Ch-2ppt.pptxCh-2ppt.pptx
Ch-2ppt.pptx
 
Lecture 9
Lecture 9Lecture 9
Lecture 9
 
Cuối cùng cũng đã chuẩn bị slide xong cho seminar ngày mai. Mai seminar đầu t...
Cuối cùng cũng đã chuẩn bị slide xong cho seminar ngày mai. Mai seminar đầu t...Cuối cùng cũng đã chuẩn bị slide xong cho seminar ngày mai. Mai seminar đầu t...
Cuối cùng cũng đã chuẩn bị slide xong cho seminar ngày mai. Mai seminar đầu t...
 
oops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaoops concept in java | object oriented programming in java
oops concept in java | object oriented programming in java
 
Java02
Java02Java02
Java02
 
03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots
 
03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots
 
object oriented programming using java, second sem BCA,UoM
object oriented programming using java, second sem BCA,UoMobject oriented programming using java, second sem BCA,UoM
object oriented programming using java, second sem BCA,UoM
 
C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorials
 

Recently uploaded

Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designMIPLM
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersSabitha Banu
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Jisc
 
Planning a health career 4th Quarter.pptx
Planning a health career 4th Quarter.pptxPlanning a health career 4th Quarter.pptx
Planning a health career 4th Quarter.pptxLigayaBacuel1
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfSpandanaRallapalli
 
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxGrade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxChelloAnnAsuncion2
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfMr Bounab Samir
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...JhezDiaz1
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomnelietumpap1
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
ROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint PresentationROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint PresentationAadityaSharma884161
 
Atmosphere science 7 quarter 4 .........
Atmosphere science 7 quarter 4 .........Atmosphere science 7 quarter 4 .........
Atmosphere science 7 quarter 4 .........LeaCamillePacle
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPCeline George
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...Nguyen Thanh Tu Collection
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptxSherlyMaeNeri
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementmkooblal
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPCeline George
 

Recently uploaded (20)

Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-design
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginners
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...
 
Planning a health career 4th Quarter.pptx
Planning a health career 4th Quarter.pptxPlanning a health career 4th Quarter.pptx
Planning a health career 4th Quarter.pptx
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdf
 
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxGrade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choom
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
ROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint PresentationROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint Presentation
 
Atmosphere science 7 quarter 4 .........
Atmosphere science 7 quarter 4 .........Atmosphere science 7 quarter 4 .........
Atmosphere science 7 quarter 4 .........
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERP
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptx
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of management
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERP
 

Java Reflection Concept and Working

  • 1. Advanced Java ProgrammingLecture-02: Reflection Aatif Kamal, Dept. of Computing Aatif.kamal@seecs.edu.pk Study Source: http://download.oracle.com/javase/tutorial/reflect/
  • 2. Reflection Overview Reflection API The “Class" class Class methods Array class Member interface Method class invoking a method, throwing exceptions Field class accessible objects
  • 3. Background Programs are just another kind of data Source code is text Manipulate it line by line, or by parsing expressions Compiled programs are data, too Integers and strings are bytes in memory that you interpret a certain way Instructions in methods are just bytes too No reason why a program can't inspect itself
  • 4. How objects work Every object is either a reference or primitive type. object class Point { public Point(int x, int y) {  } public getX() {} public getY() {} protected int x, y; } 5 x 3 y class {…} Point(int,int) {…} getX() {…} getY()
  • 5. 5 Defining Reflection Introduced in Java 1.1. Called the "Java Core Reflection API" Reflection is commonly used by programs which require the ability to examine or modify the runtime behavior of applications running in the Java virtual machine Allows you to find out information about any object, including its methods and fields, at run time. Can no longer get away with this called an enabling technology because it supports Java language elements such as: Java Beans, Serialization, and Remote Method Invocation (RMI). JBoss, Tomcat, Eclipse, etc. are reflection-based
  • 6. 6 Reflection Can be Used To . . . construct new class instances and new arrays access and modify fields of objects and classes invoke methods on objects and classes access and modify elements of arrays
  • 7. Uses of Reflection Extensibility Features An application may make use of 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 aid the developer in writing correct code. Debuggers and Test Tools Debuggers need to be able to examine private members on classes. Test harnesses can make use of reflection to systematically call a discoverable set APIs defined on a class, to insure a high level of code coverage in a test suite.
  • 8. Drawbacks of Reflection Reflection is powerful, but should not be used indiscriminately. If it is possible to perform an operation without using reflection, then it is preferable to avoid using it. Performance Overhead Because reflection involves types that are dynamically resolved, certain Java virtual machine optimizations can not be performed. Slower performance than their non-reflective counterparts, should be avoided in sections of code which are called frequently in performance-sensitive applications. Security Restrictions Reflection requires a runtime permission which may not be present when running under a security manager. Code which has to run in a restricted security context, such as in an Applet.
  • 9. Drawbacks of Reflection Exposure of Internals Since reflection allows code to perform operations that would be illegal in non-reflective code, Accessing private fields and methods, the use of reflection can result in unexpected side-effects, Reflective code breaks abstractions and therefore may change behavior with upgrades of the platform.
  • 10. Class c = Class.forName(“java.lang.String”); Object o = c.newInstance(); Reflection - Classes Reflection is a dynamic language feature Used to query object and class information static Class Class.forName(String className) Obtain a java.lang.Class object i.e. Class.forName(“java.lang.String”) gets an object corresponding to class String Object Class.newInstance() Object constructor in disguise Create a new object of a given class This makes a new empty string.
  • 11. Running Example Most typical use of reflection: Take a class name, make a Class object Create object of that class, cast and use it Statically convert Class.newInstancenew T() 1. String className = ...; 2. Class c = Class.forName(className); 3. Object o = c.newInstance(); 4. T t = (T) o; new T1(); new T2(); ...
  • 12. 12 Reflection API Package java.lang.reflect Field class get name and access for an arbitrary field Method class get info about an arbitrary method (and invoke it) Constructor class get info about an arbitrary constructor (and invoke it) Classclass creates new instances of Field, Method, and Constructor Array class static methods to create and get info about arbitrary arrays ….. With the exception of java.lang.reflect.ReflectPermission, none of the classes in java.lang.reflect have public constructors.
  • 13. java.lang.Class For every type of object, the Java virtual machine instantiates an immutable instance of java.lang.Class Class objects represent a loaded class Provides methods to examine the runtime properties of the object its methods its fields its superclass the interfaces it implements whether it's an array Provides the ability to create new classes and objects. Entry point for all of the Reflection APIs
  • 14. 14 Obtaining a Class Object To get to these classes, it is necessary to invoke appropriate methods on Class. At compile time, using the symbolic class name: Class c1 = String.class; Class c2 = Employee[].class; At runtime, by calling getClass( ) on any object: Class c3 = obj.getClass( ); At runtime, by passing a class name (string) to the forName( ) static method: Class c = Class.forName( "java.util.Date" );
  • 15. Retrieving Class Objects - Examples Object.getClass() the simplest way to get its Class is to invoke Object.getClass() Class c = "foo".getClass();  Returns the Class for String Class c = System.console().getClass();  the Class corresponding to java.io.Console. enum E { A, B }; Class c = A.getClass(); A is is an instance of the enum E; thus getClass() returns the Class corresponding to the enumeration type E. byte[] bytes = new byte[1024]; Class c = bytes.getClass(); Since arrays are Objects, it is also possible to invoke getClass() on an instance of an array. The returned Class corresponds to an array with component type byte.
  • 16. Retrieving Class Objects - Examples The .class Syntax If the type is available but there is no instance then it is possible to obtain a Class by appending ".class" to the name of the type. This is also the easiest way to obtain the Class for a primitive type. boolean b; Class c = b.getClass(); // compile-time error Class c = boolean.class; // correct Class c = java.io.PrintStream.class; Class c = int[ ][ ][ ].class;
  • 17. Retrieving Class Objects - Examples Class.forName() If the fully-qualified name of a class is available, it is possible to get the corresponding Class using the static method Class.forName() Class driverObject = Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver"); Class c = Class.forName("com.duke.MyLocaleServiceProvider") TYPE Field for Primitive Type Wrappers Two ways .class syntax, more convenient and the preferred way Class c = boolean.class;Class c1 = String.class;Class c2 = Employee[].class; All primitive types & void has a wrapper class in java.lang, used for boxing of primitive types to reference types. Each wrapper class contains a field named TYPE which is equal to the Class for the primitive type being wrapped. Class c = Double.TYPE;
  • 18. 18 Class Methods(1 of 4) public String getName( ); Returns the name of the class referred to by the Class object. public booleanisInterface( ); Returns true if the Class object refers to an interface. public booleanisArray( ); Returns true if the Class object refers to an array type. public Class getSuperclass( ); Returns the superclass of the current Class object.
  • 19. 19 Class Methods (2 of 4) public Class[] getInterfaces( ); Returns array of interface classes implemented by this class. public Class[] getClasses( ); Returns array of inner classes within this class. public Object newInstance( ); Creates and returns an instance of this class. public static Class forName( String name ); Returns a Class object corresponding to a class name (static method)
  • 20. 20 Class Methods (3 of 4) public Constructor[] getConstructors( ); Returns an array of all public constructors in the current class. (import java.lang.reflect.Constructor) public Method[] getDeclaredMethods( ); Returns an array of all public and private methods declared in the current class or interface. (import java.lang.reflect.Method) public Method[] getMethods( ); Returns an array of all public methods in the current class, as well as those in all superclasses and superinterfaces.
  • 21. Code Examples ReflectMethod.java & ReflectMethod2.java Class, Parent Class, Package name Show all methods name, signatures – use getMethods() Bypassing Abstraction SpecificMethodInfoDemo.java Showing method directly using getMethod() Bridge method Concept SampleInvoke .java,RunMethod.java & InovkeMain.java How to execute a method – using Method.invoke() Recursion through Reflection PrivateMethod.java Executing private methods of a class
  • 22. 22 Member Interface Implemented by Constructor, Method, and Field Class getDeclaringClass( ) returns the Class object representing the class or interface that declares the member or constructor represented by this Member. intgetModifiers( ) returns the Java language modifiers for the member or constructor represented by this Member, as an integer. String getName( ) returns the simple name of the underlying member or constructor represented by this Member.
  • 23. 23 Using a Method Object Using a Method object, you can... get its name and parameter list and invoke the method Obtain a Method from a signature, or get a list of all methods. To specify the signature, create an array of Class objects representing the method’s parameter types. Array will be zero-length if no parameters Special Class objects for primitives
  • 24. 24 Representing the Primitive Types Special Class objects representing the eight primitive types: Byte.TYPE, Character.TYPE, Integer.TYPE, Long.TYPE, Short.TYPE, Double.TYPE, Float.TYPE, Boolean.TYPE Void Class type: Void.TYPE Also Class types for arrays, such as ... class type for int[ ] is Integer.TYPE[].class class type for int[ ][ ] is Integer.TYPE[][].class
  • 25. 25 Method Class public class Method implements Member { public Class getReturnType( ); public Class[] getParameterTypes( ); public String getName( ); public intgetModifiers( ); public Class[] getExceptionTypes( ); public Object invoke( Object obj, Object[] args); } The modifiers are stored as a bit pattern; class Modifier has methods to interpret the bits.
  • 26. 26 Method Examples Retrieve the name of a method: Method meth = c1.getDeclaredMethods( ); String name = meth.getName( ); Retrieve an array of parameter types: Class parms[] = meth.getParameterTypes( ); Retrieve a method's return type: Class retType = meth.getReturnType( );
  • 27. 27 Method.invoke( ) public Object invoke(Object obj, Object[] args) If the parameters or return types are primitives, they are wrapped using one of the eight wrapper classes. example: Integer.TYPE The first parameter to invoke is the controlling object (use null for static methods) The second parameter is the parameter list array of objects Disadvantages to using invoke( ): executes more slowly than static invocation you have to handle all checked exceptions you lose lots of compile-time checks
  • 28. 28 Exceptions and Invoke( ) If invoked method throws an exception, invoke( ) will throw an InvocationTargetException get the actual exception by calling getException Lots of other exceptions to worry about before you call invoke: Did class load? ClassNotFoundException Was method found? NoSuchMethodException Can you access method? IllegalAccessException
  • 29. 29 Example: Invoking main( ) Calling: main( String[] args ) Simplified, with no error checking: Class cl = Class.forName( className ); Class[] paramTypes = new Class[] { String[].class }; Method m = cl.getDeclaredMethod( "main", paramTypes ); Object[] args = new Object[] { new String[] { "Breathing", "Fire" } } m.invoke( null, args );
  • 30. 30 Invoking a Constructor Call getConstructor( ), then call newInstance( ) catch InstantiationException Class c1 = Class.forName("Villain"); Class[] paramTypes = new Class[] {String.class,Integer.TYPE }; Constructor m = c1.getConstructor( paramTypes ); Object[] arguments = new Object[] { "Darth Vader", new Integer(20) }; Villan v = (Villan) m.newInstance(arguments);
  • 31. 31 Member Interface Implemented by Constructor, Method, and Field Class getDeclaringClass( ) returns the Class object representing the class or interface that declares the member or constructor represented by this Member. intgetModifiers( ) returns the Java language modifiers for the member or constructor represented by this Member, as an integer. String getName( ) returns the simple name of the underlying member or constructor represented by this Member.
  • 32. Code Examples ReflectMethod.java & ReflectMethod2.java Class, Parent Class, Package name Show all methods name, signatures – use getMethods() Bypassing Abstraction SpecificMethodInfoDemo.java Showing method directly using getMethod() Bridge method Concept SampleInvoke .java,RunMethod.java & InovkeMain.java How to execute a method – using Method.invoke() Recursion through Reflection PrivateMethod.java Executing private methods of a class
  • 33. 33 The Array Class import java.lang.reflect.Array; public class Array { // all static methods: public int getLength( Object arr ); public Object newInstance( Class elements, int length ); public Object get( Object arr, int index ); public void set( Object arr, int index, Object val ); // Various specialized versions, such as... public int getInt( Object arr, int index ); public void setInt( Object arr, int index, int val ); }
  • 34. 34 Array Samples Canine[] kennel = new Canine[10]; . int n = Array.getLength( kennel ); // set the contents of an array element Array.set( kennel, (n-1), new Canine( "Spaniel" ) ); // get an object from the array, determine its class, // and display its value: Object obj = Array.get( kennel, (n-1) ); Class c1 = obj.getClass( ); System.out.println( c1.getName( ) + "-->" + obj.toString( ) );
  • 35. 35 Two Ways to Declare an Array // first: Canine kennel = new Canine[10]; // second: Class c1 = Class.forName( "Canine" ); Canine kennel = (Canine[]) Array.newInstance( c1, 10 ); next: expanding an Array
  • 36. 36 Example: Expanding an Array Problem statement: write a function that receives an arbitrary array, allocates storage for twice the size of the array, copies the data to the new array, and returns the new array
  • 37. 37 Example: Expanding an Array Why won't this code work? public static Object[] doubleArrayBad( Object[] arr ) { intnewSize = arr.length * 2 + 1; Object[] newArray = new Object[ newSize ]; for( inti = 0; i < arr.length; i++ ) newArray[ i ] = arr[ i ]; return newArray; }
  • 38. 38 Example: Expanding an Array Ans: This method always returns an array of Object, rather than the type of the array being copied. public static Object[] doubleArrayBad( Object[] arr ) { intnewSize = arr.length * 2 + 1; Object[] newArray = new Object[ newSize ]; for( inti = 0; i < arr.length; i++ ) newArray[ i ] = arr[ i ]; return newArray; }
  • 39. 39 Example: Expanding an Array Use reflection to get the array type: public Object[] doubleArray( Object[] arr ) { Class c1 = arr.getClass( ); if( !c1.isArray( ) ) return null; intoldSize = Array.getLength( arr ); intnewSize = oldSize * 2 + 1; Object[] newArray = (Object[]) Array.newInstance( c1.getComponentType( ), newSize ); for( inti = 0; i < arr.length; i++ ) newArray[ i ] = arr[ i ]; return newArray; } see ReflectionArrayTestjava
  • 40. Assignment 02 Extension One to Assignment 01 Send a class object from one machine to another machine On recipient side through reflection show complete description of object Class, Parent class, Package, interface implemented Class Properties, their access modifier, datatype, name & value Class methods, list all methods, access modifiers, static/non static, return Type, Name of method, Input parameters, exceptions And execute any static method object on the recipient side. Save this assignment code as different version.
  • 41. Next Lecture Java Logging - Log4J