SlideShare une entreprise Scribd logo
1  sur  19
Reflection DhrubojyotiKayal
Java's Reflection API's makes it possible to inspect classes, interfaces, fields and methods at runtime, without knowing the names of the classes, methods etc. at compile time It is also possible to instantiate new objects, invoke methods and get/set field values using reflection What is reflection?
Using Java Reflection you can inspect Java classes at runtime From the classes you can obtain information about  Class Name Class Modifies (public, private, synchronized etc.) Package Info Superclass Implemented Interfaces Constructors Methods Fields Annotations Classes
First step in reflection is to get hold of the Class object When you know the name at compile time Class myObjectClass = MyObject.class If you don't know the name at compile time, but have the class name as a string at runtime or from some configuration file String className = Class.forName(className);  className = fully qualified class name ClassNotFoundException Class object
From a Class object you can obtain its name in two versions Fully qualified String className = aClass.getName();  Simple name String simpleClassName = aClass.getSimpleName();  Class Name
You can access the modifiers of a class via the Class object The class modifiers are the keywords "public", "private", "static" etc int modifiers = aClass.getModifiers();  You can check the modifiers using these methods in the class java.lang.reflect.Modifiers:  Modifiers.isAbstract(int modifiers)  Modifiers.isFinal(intmodifiers)  Modifiers.isInterface(intmodifiers)  Modifiers.isNative(intmodifiers)  Modifiers.isPrivate(intmodifiers)  Modifiers.isProtected(intmodifiers)  Modifiers.isPublic(intmodifiers)  Modifiers.isSynchronized(intmodifiers)  Modifiers.isTransient(intmodifiers)  Modifiers
Package package = aClass.getPackage(); Package Information
Class superclass = aClass.getSuperclass();  The superclass class object is a Class object like any other, so you can continue doing class reflection on that too.  Superclass
Class[] interfaces = aClass.getInterfaces();  A class can implement many interfaces. Therefore an array of Class is returned.  Interfaces are also represented by Class objects in Java Reflection.  To get a complete list of the interfaces implemented by a given class you will have to consult both the class and its superclasses recursively.  Implemented interfaces
Constructor[] constructors = aClass.getConstructors();  Method[] method = aClass.getMethods();  Method[] method = aClass.getFields();  Annotation[] annotations = aClass.getAnnotations();  Other information
Gettting specific constructor Constructor constructor = aClass.getConstructor(new Class[]{String.class});  If no constructor matches the given constructor arguments, in this case String.class, a NoSuchMethodException is thrown.  You can read what parameters a given constructor takes like this:  Class[] parameterTypes = constructor.getParameterTypes();  Constructor
Constructor constructor = MyObject.class.getConstructor(String.class);  MyObjectmyObject = (MyObject) constructor.newInstance("constructor-arg1");  Instantiate object sans new
Class aClass = ...//obtain class object  Field[] fields = aClass.getFields();  The Field[] array will have one Field instance for each public field declared in the class If you know the name of the field you want to access, you can access it like this Class aClass = MyObject.class Field field = aClass.getField("someField");  Fields
String fieldName = field.getName();  Object fieldType = field.getType(); Getting and Setting Field Values Class aClass = MyObject.class Field field = aClass.getField("someField"); MyObjectobjectInstance = new MyObject(); Object value = field.get(objectInstance); field.set(objetInstance, value);   Fields
Class aClass = ...//obtain class object Method[] methods = aClass.getMethods();  The Method[] array will have one Method instance for each public method declared in the class.  Get the public method named "doSomething“ Method method = aClass.getMethod("doSomething", new Class[]{String.class});  NoSuchMethodException Get no argument method Method method = aClass.getMethod("doSomething", null);  Methods
Method parameters parameterTypes= method.getParameterTypes();  Return type Class returnType = method.getReturnType();  Methods
//get method that takes a String as argument Method method = MyObject.class.getMethod("doSomething", String.class);  Object returnValue = method.invoke(myInstance, "parameter-value1");  Execute a static method? Invoking methods
Dynamic code addition at runtime Building frameworks. Why is reflection important?
Q&A

Contenu connexe

Tendances

Introduction to class in java
Introduction to class in javaIntroduction to class in java
Introduction to class in javakamal kotecha
 
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteChapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteTushar B Kute
 
Java lec class, objects and constructors
Java lec class, objects and constructorsJava lec class, objects and constructors
Java lec class, objects and constructorsJan Niño Acierto
 
Lect 1-java object-classes
Lect 1-java object-classesLect 1-java object-classes
Lect 1-java object-classesFajar Baskoro
 
Class and object in c++
Class and object in c++Class and object in c++
Class and object in c++NainaKhan28
 
The Ring programming language version 1.2 book - Part 53 of 84
The Ring programming language version 1.2 book - Part 53 of 84The Ring programming language version 1.2 book - Part 53 of 84
The Ring programming language version 1.2 book - Part 53 of 84Mahmoud Samir Fayed
 
Java basic tutorial
Java basic tutorialJava basic tutorial
Java basic tutorialBui Kiet
 
The Ring programming language version 1.2 book - Part 52 of 84
The Ring programming language version 1.2 book - Part 52 of 84The Ring programming language version 1.2 book - Part 52 of 84
The Ring programming language version 1.2 book - Part 52 of 84Mahmoud Samir Fayed
 
How to write you first class in c++ object oriented programming
How to write you first class in c++ object oriented programmingHow to write you first class in c++ object oriented programming
How to write you first class in c++ object oriented programmingSyed Faizan Hassan
 
Python Class | Python Programming | Python Tutorial | Edureka
Python Class | Python Programming | Python Tutorial | EdurekaPython Class | Python Programming | Python Tutorial | Edureka
Python Class | Python Programming | Python Tutorial | EdurekaEdureka!
 

Tendances (20)

Java chapter 5
Java chapter 5Java chapter 5
Java chapter 5
 
Java chapter 4
Java chapter 4Java chapter 4
Java chapter 4
 
Java Methods
Java MethodsJava Methods
Java Methods
 
Introduction to class in java
Introduction to class in javaIntroduction to class in java
Introduction to class in java
 
C# classes objects
C#  classes objectsC#  classes objects
C# classes objects
 
Class and object in C++ By Pawan Thakur
Class and object in C++ By Pawan ThakurClass and object in C++ By Pawan Thakur
Class and object in C++ By Pawan Thakur
 
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteChapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
 
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 lec class, objects and constructors
Java lec class, objects and constructorsJava lec class, objects and constructors
Java lec class, objects and constructors
 
Constructors
ConstructorsConstructors
Constructors
 
Lect 1-java object-classes
Lect 1-java object-classesLect 1-java object-classes
Lect 1-java object-classes
 
C++ classes
C++ classesC++ classes
C++ classes
 
Class and object in c++
Class and object in c++Class and object in c++
Class and object in c++
 
The Ring programming language version 1.2 book - Part 53 of 84
The Ring programming language version 1.2 book - Part 53 of 84The Ring programming language version 1.2 book - Part 53 of 84
The Ring programming language version 1.2 book - Part 53 of 84
 
Unit3 part1-class
Unit3 part1-classUnit3 part1-class
Unit3 part1-class
 
Java basic tutorial
Java basic tutorialJava basic tutorial
Java basic tutorial
 
The Ring programming language version 1.2 book - Part 52 of 84
The Ring programming language version 1.2 book - Part 52 of 84The Ring programming language version 1.2 book - Part 52 of 84
The Ring programming language version 1.2 book - Part 52 of 84
 
How to write you first class in c++ object oriented programming
How to write you first class in c++ object oriented programmingHow to write you first class in c++ object oriented programming
How to write you first class in c++ object oriented programming
 
Python Class | Python Programming | Python Tutorial | Edureka
Python Class | Python Programming | Python Tutorial | EdurekaPython Class | Python Programming | Python Tutorial | Edureka
Python Class | Python Programming | Python Tutorial | Edureka
 
Classes and objects
Classes and objectsClasses and objects
Classes and objects
 

En vedette

Bsl Travel Pix
Bsl Travel PixBsl Travel Pix
Bsl Travel Pixsporck
 
Seex feet under ibgles
Seex feet under ibglesSeex feet under ibgles
Seex feet under ibglesLidia Fonseca
 
Tak.To.Je.Ona
Tak.To.Je.OnaTak.To.Je.Ona
Tak.To.Je.Onavenom001
 
A Brief History of Conversation: Advertising in the Social Space
A Brief History of Conversation: Advertising in the Social SpaceA Brief History of Conversation: Advertising in the Social Space
A Brief History of Conversation: Advertising in the Social SpaceGordon Peters
 
01 overview-servlets-and-environment-setup
01 overview-servlets-and-environment-setup01 overview-servlets-and-environment-setup
01 overview-servlets-and-environment-setupdhrubo kayal
 
14 initialization & cleanup
14   initialization & cleanup14   initialization & cleanup
14 initialization & cleanupdhrubo kayal
 
Le Rocce Metamorfiche
Le Rocce MetamorficheLe Rocce Metamorfiche
Le Rocce Metamorfichematteo58
 
Going Mobile @ Balboa Park
Going Mobile @ Balboa ParkGoing Mobile @ Balboa Park
Going Mobile @ Balboa ParkTitus Bicknell
 
Universal Yoga Profile
Universal Yoga ProfileUniversal Yoga Profile
Universal Yoga ProfileVijay Yoga
 
Helicopter Assessments - Improve your Customer Data Security!
Helicopter Assessments - Improve your Customer Data Security!Helicopter Assessments - Improve your Customer Data Security!
Helicopter Assessments - Improve your Customer Data Security!Dahamoo GmbH
 
Valve Interactive Capabilities 2008
Valve Interactive Capabilities 2008Valve Interactive Capabilities 2008
Valve Interactive Capabilities 2008dtjobrien
 
Sencha Complete: Kharkiv JS #1
Sencha Complete: Kharkiv JS #1Sencha Complete: Kharkiv JS #1
Sencha Complete: Kharkiv JS #1Illya Klymov
 
Hot Chocolate - Chocolate Caliente
Hot Chocolate  -  Chocolate CalienteHot Chocolate  -  Chocolate Caliente
Hot Chocolate - Chocolate CalienteEduardo Cortes
 
Introduction To Lisp
Introduction To LispIntroduction To Lisp
Introduction To Lispkyleburton
 
Fuzzy String Matching
Fuzzy String MatchingFuzzy String Matching
Fuzzy String Matchingkyleburton
 

En vedette (19)

Bsl Travel Pix
Bsl Travel PixBsl Travel Pix
Bsl Travel Pix
 
12 encapsulation
12   encapsulation12   encapsulation
12 encapsulation
 
Seex feet under ibgles
Seex feet under ibglesSeex feet under ibgles
Seex feet under ibgles
 
Asd
AsdAsd
Asd
 
Tak.To.Je.Ona
Tak.To.Je.OnaTak.To.Je.Ona
Tak.To.Je.Ona
 
A Brief History of Conversation: Advertising in the Social Space
A Brief History of Conversation: Advertising in the Social SpaceA Brief History of Conversation: Advertising in the Social Space
A Brief History of Conversation: Advertising in the Social Space
 
01 overview-servlets-and-environment-setup
01 overview-servlets-and-environment-setup01 overview-servlets-and-environment-setup
01 overview-servlets-and-environment-setup
 
14 initialization & cleanup
14   initialization & cleanup14   initialization & cleanup
14 initialization & cleanup
 
Le Rocce Metamorfiche
Le Rocce MetamorficheLe Rocce Metamorfiche
Le Rocce Metamorfiche
 
Going Mobile @ Balboa Park
Going Mobile @ Balboa ParkGoing Mobile @ Balboa Park
Going Mobile @ Balboa Park
 
Universal Yoga Profile
Universal Yoga ProfileUniversal Yoga Profile
Universal Yoga Profile
 
Cipla 20-09-2010
Cipla   20-09-2010Cipla   20-09-2010
Cipla 20-09-2010
 
Helicopter Assessments - Improve your Customer Data Security!
Helicopter Assessments - Improve your Customer Data Security!Helicopter Assessments - Improve your Customer Data Security!
Helicopter Assessments - Improve your Customer Data Security!
 
Valve Interactive Capabilities 2008
Valve Interactive Capabilities 2008Valve Interactive Capabilities 2008
Valve Interactive Capabilities 2008
 
Sencha Complete: Kharkiv JS #1
Sencha Complete: Kharkiv JS #1Sencha Complete: Kharkiv JS #1
Sencha Complete: Kharkiv JS #1
 
Hot Chocolate - Chocolate Caliente
Hot Chocolate  -  Chocolate CalienteHot Chocolate  -  Chocolate Caliente
Hot Chocolate - Chocolate Caliente
 
Intro To Git
Intro To GitIntro To Git
Intro To Git
 
Introduction To Lisp
Introduction To LispIntroduction To Lisp
Introduction To Lisp
 
Fuzzy String Matching
Fuzzy String MatchingFuzzy String Matching
Fuzzy String Matching
 

Similaire à 19 reflection

Similaire à 19 reflection (20)

Java Reflection Concept and Working
Java Reflection Concept and WorkingJava Reflection Concept and Working
Java Reflection Concept and Working
 
Java Reflection
Java ReflectionJava Reflection
Java Reflection
 
Java Reflection
Java ReflectionJava Reflection
Java Reflection
 
UNIT - IIInew.pptx
UNIT - IIInew.pptxUNIT - IIInew.pptx
UNIT - IIInew.pptx
 
Sonu wiziq
Sonu wiziqSonu wiziq
Sonu wiziq
 
packages and interfaces
packages and interfacespackages and interfaces
packages and interfaces
 
Reflection
ReflectionReflection
Reflection
 
VP-303 lecture#9.pptx
VP-303 lecture#9.pptxVP-303 lecture#9.pptx
VP-303 lecture#9.pptx
 
Lecture 9
Lecture 9Lecture 9
Lecture 9
 
9781439035665 ppt ch10
9781439035665 ppt ch109781439035665 ppt ch10
9781439035665 ppt ch10
 
Chap-2 Classes & Methods.pptx
Chap-2 Classes & Methods.pptxChap-2 Classes & Methods.pptx
Chap-2 Classes & Methods.pptx
 
Reflection in java
Reflection in javaReflection in java
Reflection in java
 
Ch-2ppt.pptx
Ch-2ppt.pptxCh-2ppt.pptx
Ch-2ppt.pptx
 
Java02
Java02Java02
Java02
 
Defining classes-and-objects-1.0
Defining classes-and-objects-1.0Defining classes-and-objects-1.0
Defining classes-and-objects-1.0
 
Classes and Objects in C#
Classes and Objects in C#Classes and Objects in C#
Classes and Objects in C#
 
Classes & objects new
Classes & objects newClasses & objects new
Classes & objects new
 
Inheritance
InheritanceInheritance
Inheritance
 
constructors.pptx
constructors.pptxconstructors.pptx
constructors.pptx
 
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
 

Plus de dhrubo kayal

Plus de dhrubo kayal (18)

01 session tracking
01   session tracking01   session tracking
01 session tracking
 
03 handling requests
03 handling requests03 handling requests
03 handling requests
 
02 up close with servlets
02 up close with servlets02 up close with servlets
02 up close with servlets
 
18 concurrency
18   concurrency18   concurrency
18 concurrency
 
17 exceptions
17   exceptions17   exceptions
17 exceptions
 
16 containers
16   containers16   containers
16 containers
 
15 interfaces
15   interfaces15   interfaces
15 interfaces
 
13 inheritance
13   inheritance13   inheritance
13 inheritance
 
11 static
11   static11   static
11 static
 
10 access control
10   access control10   access control
10 access control
 
09 packages
09   packages09   packages
09 packages
 
08 class and object
08   class and object08   class and object
08 class and object
 
07 flow control
07   flow control07   flow control
07 flow control
 
05 operators
05   operators05   operators
05 operators
 
04 data types & variables
04   data types & variables04   data types & variables
04 data types & variables
 
03 hello world with java
03   hello world with java03   hello world with java
03 hello world with java
 
02 what is java
02   what is java02   what is java
02 what is java
 
01 handshake
01   handshake01   handshake
01 handshake
 

19 reflection

  • 2. Java's Reflection API's makes it possible to inspect classes, interfaces, fields and methods at runtime, without knowing the names of the classes, methods etc. at compile time It is also possible to instantiate new objects, invoke methods and get/set field values using reflection What is reflection?
  • 3. Using Java Reflection you can inspect Java classes at runtime From the classes you can obtain information about Class Name Class Modifies (public, private, synchronized etc.) Package Info Superclass Implemented Interfaces Constructors Methods Fields Annotations Classes
  • 4. First step in reflection is to get hold of the Class object When you know the name at compile time Class myObjectClass = MyObject.class If you don't know the name at compile time, but have the class name as a string at runtime or from some configuration file String className = Class.forName(className); className = fully qualified class name ClassNotFoundException Class object
  • 5. From a Class object you can obtain its name in two versions Fully qualified String className = aClass.getName(); Simple name String simpleClassName = aClass.getSimpleName(); Class Name
  • 6. You can access the modifiers of a class via the Class object The class modifiers are the keywords "public", "private", "static" etc int modifiers = aClass.getModifiers(); You can check the modifiers using these methods in the class java.lang.reflect.Modifiers: Modifiers.isAbstract(int modifiers) Modifiers.isFinal(intmodifiers) Modifiers.isInterface(intmodifiers) Modifiers.isNative(intmodifiers) Modifiers.isPrivate(intmodifiers) Modifiers.isProtected(intmodifiers) Modifiers.isPublic(intmodifiers) Modifiers.isSynchronized(intmodifiers) Modifiers.isTransient(intmodifiers) Modifiers
  • 7. Package package = aClass.getPackage(); Package Information
  • 8. Class superclass = aClass.getSuperclass(); The superclass class object is a Class object like any other, so you can continue doing class reflection on that too. Superclass
  • 9. Class[] interfaces = aClass.getInterfaces(); A class can implement many interfaces. Therefore an array of Class is returned. Interfaces are also represented by Class objects in Java Reflection. To get a complete list of the interfaces implemented by a given class you will have to consult both the class and its superclasses recursively. Implemented interfaces
  • 10. Constructor[] constructors = aClass.getConstructors(); Method[] method = aClass.getMethods(); Method[] method = aClass.getFields(); Annotation[] annotations = aClass.getAnnotations(); Other information
  • 11. Gettting specific constructor Constructor constructor = aClass.getConstructor(new Class[]{String.class}); If no constructor matches the given constructor arguments, in this case String.class, a NoSuchMethodException is thrown. You can read what parameters a given constructor takes like this: Class[] parameterTypes = constructor.getParameterTypes(); Constructor
  • 12. Constructor constructor = MyObject.class.getConstructor(String.class); MyObjectmyObject = (MyObject) constructor.newInstance("constructor-arg1"); Instantiate object sans new
  • 13. Class aClass = ...//obtain class object Field[] fields = aClass.getFields(); The Field[] array will have one Field instance for each public field declared in the class If you know the name of the field you want to access, you can access it like this Class aClass = MyObject.class Field field = aClass.getField("someField"); Fields
  • 14. String fieldName = field.getName(); Object fieldType = field.getType(); Getting and Setting Field Values Class aClass = MyObject.class Field field = aClass.getField("someField"); MyObjectobjectInstance = new MyObject(); Object value = field.get(objectInstance); field.set(objetInstance, value); Fields
  • 15. Class aClass = ...//obtain class object Method[] methods = aClass.getMethods(); The Method[] array will have one Method instance for each public method declared in the class. Get the public method named "doSomething“ Method method = aClass.getMethod("doSomething", new Class[]{String.class}); NoSuchMethodException Get no argument method Method method = aClass.getMethod("doSomething", null); Methods
  • 16. Method parameters parameterTypes= method.getParameterTypes(); Return type Class returnType = method.getReturnType(); Methods
  • 17. //get method that takes a String as argument Method method = MyObject.class.getMethod("doSomething", String.class); Object returnValue = method.invoke(myInstance, "parameter-value1"); Execute a static method? Invoking methods
  • 18. Dynamic code addition at runtime Building frameworks. Why is reflection important?
  • 19. Q&A