SlideShare a Scribd company logo
SINF2335:Prog.Paradigms:
Theory,Pract.andApplic.
Lecture 9 :

Basics of Reflection in Java
LSINF 2335
Programming Paradigms
Prof. Kim Mens
UCL / EPL / INGI
(Slides partly based on the

book “Java Reflection in Action”, on
The Java Tutorials, and on

slides by Pr. Walter Cazzola)
SINF2335:Prog.Paradigms:
Theory,Pract.andApplic.
Some References
2
Ira R. Forman
Nate Forman
M A N N I N G
Sample Chapter
SINF2335:Prog.Paradigms:
Theory,Pract.andApplic.
Basics of Reflection in Java
■ About reflection in Java
■ Example of a reflective Java program
■ The Java meta-object protocol
■ The Java reflection API
– Class
– Field, Method and Constructor
■ Metaclass madness
■ Java's dynamic proxies
■ Reflective features in Java 1.5
3
SINF2335:Prog.Paradigms:
Theory,Pract.andApplic.
Basics of Reflection in Java
■ About reflection in Java
■ Example of a reflective Java program
■ The Java meta-object protocol
■ The Java reflection API
– Class
– Field, Method and Constructor
■ History of reflection in Java
4
SINF2335:Prog.Paradigms:
Theory,Pract.andApplic. Reflection, reification,
introspection & intercession
■ (Computational) reflection: ability of a running
program to inspect and change itself.
■ Reification: making the language concepts (meta-
level) accessible (at base level) to the program, so
that they can be manipulated as ordinary data.
■ Introspection: self-examination; only looking at
the reified entities.
■ Intercession: when you actually intervene in the
program execution as well (by manipulating those
reified entities)
5
SINF2335:Prog.Paradigms:
Theory,Pract.andApplic.
6
About Reflection in Java
■ Java provides an API for reflection
– a rich set of operations for introspection
– few intercession capabilities
■ Can be used to examine or modify the runtime
behaviour of applications running in the JVM
■ Warning
– is a pretty advanced feature
• should be used only by developers who have a strong grasp of the
fundamentals of the language
– when to avoid it
• in performance-sensitive applications
• in security-related code
• may expose some internals (e.g. accessing of private fields)
SINF2335:Prog.Paradigms:
Theory,Pract.andApplic.
Basics of Reflection in Java
■ About reflection in Java
■ Example of a reflective Java program
■ The Java meta-object protocol
■ The Java reflection API
– Class
– Field, Method and Constructor
■ History of reflection in Java
7
SINF2335:Prog.Paradigms:
Theory,Pract.andApplic.
An Illustrative Example
8
(Taken from Chapter 1 of the
book “Java Reflection in
Action” by Forman & Forman.)
■ User interface implementation
■ Contains several visual components (classes)
– some developed in-house
– some open source
– some belong the standard Java libraries
– some are bought
■ All these components understand
– setColor(Color aColor)
■ Problem: how to invoke this method?
– the components share no common supertype of interface
– only common base class is Object
SINF2335:Prog.Paradigms:
Theory,Pract.andApplic.
public class Component4 {
Color myColor;
public void setColor(Color color) {
myColor = color;
}
...
}
public class Component3 {
Color myColor;
public void setColor(Color color) {
myColor = color;
}
...
}
An Illustrative Example
9
public class Component1 {
Color myColor;
public void setColor(Color color) {
myColor = color;
}
...
}
public class Component2 {
Color myColor;
public void setColor(Color color) {
myColor = color;
}
...
}
SINF2335:Prog.Paradigms:
Theory,Pract.andApplic.
What’s the problem?
10
public class Main {
static Object[] components = new Object[10];
static Color color = new Color(0);
public static void initializeComponents() {
components[0] = new Component1();
components[1] = new Component2();
... }
public static void main(String[] args) {
initializeComponents();
for (int i = 0; i < args.length; i++)
if (components[i] != null)
components[i].setColor(color);
}
}
The method setColor(color) is undefined for the type Object
SINF2335:Prog.Paradigms:
Theory,Pract.andApplic.
Possible solutions?
11
■ Define setColor on Object
– not a nice solution; not possible anyway
■ Use a typecast
– impossible: Object is the only common supertype
■ Make components implement common interface
– would work : we can use that interface as common type
– unfortunately some code is not ours: cannot be changed
■ Use an adapter for each component
– i.e. a “fake” component that delegates to the real one
– all adapters implement a common interface
– works, but explosion of extra classes and objects
SINF2335:Prog.Paradigms:
Theory,Pract.andApplic.
More solutions?
12
■ Use instanceOf and casting
if (components[i] instanceof Component1)
((Component1) components[i]).setColor(color);
if (components[i] instanceof Component2)
((Component2) components[i]).setColor(color);
...
– works, but code bloated with conditionals and calls
– and concrete types hard-coded in the code
■ Why not use reflection?
– to find the right setColor method to call
– and invoke it using reflection
SINF2335:Prog.Paradigms:
Theory,Pract.andApplic.
Reflective solution
13
public class Main {
static Object[] components = new Object[10];
static Color color = new Color(0);
public static void initializeComponents() {
components[0] = new Component1();
components[1] = new Component2();
... }
public static void main(String[] args) {
initializeComponents();
for (int i = 0; i < args.length; i++)
if (components[i] != null)
setObjectColor(components[i],color);
}
...
} Reflective method
SINF2335:Prog.Paradigms:
Theory,Pract.andApplic.
Reflective solution
14
public static void setObjectColor( Object obj, Color color ) {

Class cls = obj.getClass();
try {
Method method = cls.getMethod( "setColor",
new Class[] {Color.class} );
method.invoke( obj, new Object[] {color} );
}
catch (NoSuchMethodException ex) {
throw new IllegalArgumentException(
cls.getName()
+ " does not support method setColor(Color)" );
}
catch (IllegalAccessException ex) {
throw new IllegalArgumentException(
"Insufficient access permissions to call"
+ "setColor(:Color) in class " + cls.getName());
}
catch (InvocationTargetException ex) {
throw new RuntimeException(ex);
}
}
SINF2335:Prog.Paradigms:
Theory,Pract.andApplic.
Reflective solution
15
public static void setObjectColor( Object obj, Color color ) {
Class cls = obj.getClass();
try {
Method method = cls.getMethod( "setColor",
new Class[] {Color.class} );
method.invoke( obj, new Object[] {color} );
}
catch (NoSuchMethodException ex) {
throw new IllegalArgumentException(
cls.getName()
+ " does not support method setColor(Color)" );
}
catch (IllegalAccessException ex) {
throw new IllegalArgumentException(
"Insufficient access permissions to call"
+ "setColor(:Color) in class " + cls.getName());
}
catch (InvocationTargetException ex) {
throw new RuntimeException(ex);
}
}
Query obj for its class
SINF2335:Prog.Paradigms:
Theory,Pract.andApplic.
Reflective solution
16
public static void setObjectColor( Object obj, Color color ) {
Class cls = obj.getClass();
try {
Method method = cls.getMethod( "setColor",
new Class[] {Color.class} );
method.invoke( obj, new Object[] {color} );
}
catch (NoSuchMethodException ex) {
throw new IllegalArgumentException(
cls.getName()
+ " does not support method setColor(Color)" );
}
catch (IllegalAccessException ex) {
throw new IllegalArgumentException(
"Insufficient access permissions to call"
+ "setColor(:Color) in class " + cls.getName());
}
catch (InvocationTargetException ex) {
throw new RuntimeException(ex);
}
}
Query class object
for setColor method
SINF2335:Prog.Paradigms:
Theory,Pract.andApplic.
Reflective solution
17
public static void setObjectColor( Object obj, Color color ) {
Class cls = obj.getClass();
try {
Method method = cls.getMethod( "setColor",
new Class[] {Color.class} );
method.invoke( obj, new Object[] {color} );
}
catch (NoSuchMethodException ex) {
throw new IllegalArgumentException(
cls.getName()
+ " does not support method setColor(Color)" );
}
catch (IllegalAccessException ex) {
throw new IllegalArgumentException(
"Insufficient access permissions to call"
+ "setColor(:Color) in class " + cls.getName());
}
catch (InvocationTargetException ex) {
throw new RuntimeException(ex);
}
}
Call resulting
method on target
obj
SINF2335:Prog.Paradigms:
Theory,Pract.andApplic.
Reflective solution
18
public static void setObjectColor( Object obj, Color color ) {
Class cls = obj.getClass();
try {
Method method = cls.getMethod( "setColor",
new Class[] {Color.class} );
method.invoke( obj, new Object[] {color} );
}
catch (NoSuchMethodException ex) {
throw new IllegalArgumentException(
cls.getName()
+ " does not support method setColor(Color)" );
}
catch (IllegalAccessException ex) {
throw new IllegalArgumentException(
"Insufficient access permissions to call"
+ "setColor(:Color) in class " + cls.getName());
}
catch (InvocationTargetException ex) {
throw new RuntimeException(ex);
}
}
Catch error if class
obj does not support
setColor method
SINF2335:Prog.Paradigms:
Theory,Pract.andApplic.
Reflective solution
19
public static void setObjectColor( Object obj, Color color ) {
Class cls = obj.getClass();
try {
Method method = cls.getMethod( "setColor",
new Class[] {Color.class} );
method.invoke( obj, new Object[] {color} );
}
catch (NoSuchMethodException ex) {
throw new IllegalArgumentException(
cls.getName()
+ " does not support method setColor(Color)" );
}
catch (IllegalAccessException ex) {
throw new IllegalArgumentException(
"Insufficient access permissions to call"
+ "setColor(:Color) in class " + cls.getName());
}
catch (InvocationTargetException ex) {
throw new RuntimeException(ex);
}
}
Catch error if invoker
cannot call setColor method
SINF2335:Prog.Paradigms:
Theory,Pract.andApplic.
Reflective solution
20
public static void setObjectColor( Object obj, Color color ) {
Class cls = obj.getClass();
try {
Method method = cls.getMethod( "setColor",
new Class[] {Color.class} );
method.invoke( obj, new Object[] {color} );
}
catch (NoSuchMethodException ex) {
throw new IllegalArgumentException(
cls.getName()
+ " does not support method setColor(Color)" );
}
catch (IllegalAccessException ex) {
throw new IllegalArgumentException(
"Insufficient access permissions to call"
+ "setColor(:Color) in class " + cls.getName());
}
catch (InvocationTargetException ex) {
throw new RuntimeException(ex);
}
}
Catch error if method
setColor throws exception
SINF2335:Prog.Paradigms:
Theory,Pract.andApplic.
An Illustrative Example
21
■ Introspection
– query object for its class
– query class for its methods
■ Dynamic invocation
– dynamically call method at run-time

without specifying which one at compile-time
■ Care should be taken to handle all exceptions
■ This solution is
– flexible and elegant
– though somewhat verbose
– but has some performance penalties
SINF2335:Prog.Paradigms:
Theory,Pract.andApplic.
Basics of Reflection in Java
■ About reflection in Java
■ Example of a reflective Java program
■ The Java meta-object protocol
■ The Java reflection API
– Class
– Field, Method and Constructor
■ History of reflection in Java
22
SINF2335:Prog.Paradigms:
Theory,Pract.andApplic.
The Java Meta-Object Protocol
23
Point aPoint = new Point(2,3)

aPoint.getClass()
➡ class Point
Class aClass = aPoint.getClass()

aClass.getClass()
➡ class java.lang.Class
Class aMeta = aClass.getClass()

aMeta.getClass()
➡ class java.lang.Class
Class aMetaMeta = aMeta.getClass()

aMetaMeta.getClass()
➡ class java.lang.Class
Point
aPoint
getClass()
Class
getClass()
getClass()
SINF2335:Prog.Paradigms:
Theory,Pract.andApplic.
■ Objects are instances of a class
■ Classes are instances of the meta class Class
■ The meta class Class is an instance of itself
Class Metaclass
ObjectObjectObjectObjectObject
Point Class
ObjectObjectObjectObjectaPoint
The metaclass loop in Java
instance of
SINF2335:Prog.Paradigms:
Theory,Pract.andApplic. The Java Meta-Object Protocol
Object
Class Point
instance of
subclass of
Field
Method
Constructor
Member
implements
interface
SINF2335:Prog.Paradigms:
Theory,Pract.andApplic.
Basics of Reflection in Java
■ About reflection in Java
■ Example of a reflective Java program
■ The Java meta-object protocol
■ The Java reflection API
– Class
– Field, Method and Constructor
■ History of reflection in Java
26
SINF2335:Prog.Paradigms:
Theory,Pract.andApplic.
The Java Reflection API
■ The Java Core Reflection API
– provides a small, type-safe, and secure API
– that supports introspection about the classes and
objects in the current JVM
– If permitted by security policy, the API 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
– Intercession on classes and objects is forbidden

27
SINF2335:Prog.Paradigms:
Theory,Pract.andApplic.
The Java Reflection API
■ java.lang.reflect is in a subpackage of java.lang
■ Defines the following classes and methods:
– The classes Field, Method and Constructor
• reflect class and interface members and constructors
• provide reflective information about the underlying member or
constructor
• a type-safe means to use the member or constructor to operate on
Java objects
– Methods of class Class that enable the construction of new
instances of the Field, Method and Constructor classes.
– and more...
■ There are also some parts of the java.lang package
that support reflection
– In particular the class Class 28
SINF2335:Prog.Paradigms:
Theory,Pract.andApplic.
Basics of Reflection in Java
■ About reflection in Java
■ Example of a reflective Java program
■ The Java meta-object protocol
■ The Java reflection API
– Class
– Field, Method and Constructor
■ History of reflection in Java
29
SINF2335:Prog.Paradigms:
Theory,Pract.andApplic.
Class
■ Instances of the class Class represent classes and
interfaces in a running Java application.
– Every array also belongs to a class that is reflected as a Class
object
• shared by all arrays with same element type and dimension
– Primitive Java types (boolean, byte, char, int, ...), and void are
also represented as Class objects
■ Class has no public constructor
– Class objects are constructed automatically by the Java Virtual
Machine as classes are loaded
– and by calls to defineClass method in the class loader
■ Defined in java.lang (instead of java.lang.reflect)
30
SINF2335:Prog.Paradigms:
Theory,Pract.andApplic.
Using Class: examples
■ Using a Class object to print the class name of an
object:
void printClassName(Object obj) {
System.out.println("The class of " + obj + " is "
+ obj.getClass().getName());
}
■ Getting the Class object for a named type using a
class literal:
System.out.println("The name of class Foo is:"
+ Foo.class.getName());
31
SINF2335:Prog.Paradigms:
Theory,Pract.andApplic.
Class: querying for methods
32
knows that setObjectColor always wants a method that takes one Color argument.
He specifies this using Color.class.
Class has other methods for introspecting about methods. The signatures and
return types for these methods are shown in table 1.1. As in the previous example,
the queries use an array of Class to indicate the types of the parameters. In
Table 1.1 The methods defined by Class for method query
Method Description
Method getMethod( String name,
Class[] parameterTypes )
Returns a Method object that represents a public
method (either declared or inherited) of the target
Class object with the signature specified by the
second parameters
Method[] getMethods() Returns an array of Method objects that represent
all of the public methods (either declared or inher-
ited) supported by the target Class object
Method getDeclaredMethod(
String name,
Class[] parameterTypes )
Returns a Method object that represents a
declared method of the target Class object with
the signature specified by the second parameters
Method[] getDeclaredMethods() Returns an array of Method objects that represent
all of the methods declared by the target Class
object
+ getConstructor, getField, ...
SINF2335:Prog.Paradigms:
Theory,Pract.andApplic. Class: dealing with type
representation
33
Representing types with class objects
Java represents primitive, array, and interface types by introducing class objects
represent them. These class objects cannot do everything that many other cl
objects can. For instance, you cannot create a new instance of a primitive or int
Table 1.2 Methods defined by Class that deal with type representation
Method Description
String getName() Returns the fully qualified name of the target Class object
Class getComponentType() If the target object is a Class object for an array, returns the
Class object representing the component type
boolean isArray() Returns true if and only if the target Class object repre-
sents an array
boolean isInterface() Returns true if and only if the target Class object repre-
sents an interface
boolean isPrimitive() Returns true if and only if the target Class object repre-
sents a primitive type or void
SINF2335:Prog.Paradigms:
Theory,Pract.andApplic.
Basics of Reflection in Java
■ About reflection in Java
■ Example of a reflective Java program
■ The Java meta-object protocol
■ The Java reflection API
– Class
– Field, Method and Constructor
■ History of reflection in Java
34
SINF2335:Prog.Paradigms:
Theory,Pract.andApplic.
Field, Method and Constructor
■ Three classes to reason about Java members
■ Only JVM may create instances of these classes
– i.e., they are final
■ Can be used to manipulate the underlying objects
– get reflective information about the underlying member
– get and set field values
– invoke methods on objects or classes
– create new instances of classes
■ These classes all implement the Member interface
– defines methods to query member for basic information:
• the class implementing a member
• the Java language modifiers for the member
35
SINF2335:Prog.Paradigms:
Theory,Pract.andApplic.
Field
■ A Field object represents a reified field
– may be a class variable (a static field)
– or an instance variable (a non-static field)
■ Methods of class Field are used to
– obtain the type of the field
– get and set the field’s value on objects
36
SINF2335:Prog.Paradigms:
Theory,Pract.andApplic.
Field
37
Method Description
getDeclaringClass() Returns the Class object representing the class or interface that
declares the field represented by this Field object.
getModifiers() Returns the Java language modifiers for the field represented by
this Field object, as an integer.
getName() Returns the name of the field represented by this Field object,
as String.
getType() Returns a Class object that identifies the declared type for the
field represented by this Field object.
get(Object obj) Returns the value of the field represented by this Field object,
on the specified object. The value is automatically wrapped in an
object if it has a primitive type.
set(Object obj, Object value) Sets the field represented by this Field object on the specified
object argument to the specified new value. The new value is
automatically unwrapped if the underlying field has a primitive
type.
toString() Returns a String describing this Field.
SINF2335:Prog.Paradigms:
Theory,Pract.andApplic.
Constructor
■ A Constructor object represents a reified
constructor
■ Methods of class Constructor are used to
– obtain the formal parameter types of the constructor
– get the checked exception types of the constructor
– create and initialise new instances of the class that
declares the constructor
• provided the class is instantiable
• using the method newInstance
38
SINF2335:Prog.Paradigms:
Theory,Pract.andApplic.
Constructor
39
Method Description
getDeclaringClass() Returns the Class object representing the class that declares the
constructor represented by this Constructor object.
getExceptionTypes() Returns an array of Class objects that represent the types of of
exceptions declared to be thrown by the underlying constructor
represented by this Constructor object.
getModifiers() Returns the Java language modifiers for the constructor
represented by this Constructor object, as an integer.
getName() Returns the name of this constructor, as a string.
getParameterTypes() Returns an array of Class objects that represent the formal
parameter types, in declaration order, of the constructor
represented by this Constructor object.
newInstance(Object[] initargs) Uses the constructor represented by this Constructor object to
create and initialize a new instance of the constructor's declaring
class, with the specified initialization parameters.
toString() Returns a String describing this Constructor.
SINF2335:Prog.Paradigms:
Theory,Pract.andApplic.
Method
■ A Method object represents a reified method
– may be an abstract method, an instance method or a class
(static) method
■ Methods of class Method are used to
– obtain the formal parameter types of the method
– obtain its return type
– get the checked exception types of the method
– invoke the method on target objects
• instance and abstract method invocation uses dynamic
method resolution
– based on target object’s run-time class
• static method invocation uses the static method of the
method’s declaring class
40
SINF2335:Prog.Paradigms:
Theory,Pract.andApplic.
Method
41
Understanding method objects 15
metaobjects that represent methods. Table 1.3 shows some of the methods sup-
Table 1.3 Methods defined by Method
Method Description
Class getDeclaringClass() Returns the Class object that declared the method repre-
sented by this Method object
Class[] getExceptionTypes() Returns an array of Class objects representing the types of
the exceptions declared to be thrown by the method repre-
sented by this Method object
int getModifiers() Returns the modifiers for the method represented by this
Method object encoded as an int
String getName() Returns the name of the method represented by this Method
object
Class[] getParameterTypes() Returns an array of Class objects representing the formal
parameters in the order in which they were declared
Class getReturnType() Returns the Class object representing the type returned by
the method represented by this Method object
Object invoke(Object obj, Object[] args) Invokes the method represented by this Method object on
the specified object with the arguments specified in the
Object array
SINF2335:Prog.Paradigms:
Theory,Pract.andApplic.
Basics of Reflection in Java
■ About reflection in Java
■ Example of a reflective Java program
■ The Java meta-object protocol
■ The Java reflection API
– Class
– Field, Method and Constructor
■ History of reflection in Java
42
SINF2335:Prog.Paradigms:
Theory,Pract.andApplic.
Reflection in Java.
Java Reflection API (Package java.lang.reflect)
Call Stack Introspection.
Introduction.
The Java’s Class Model.
Java’s Limitations on Reflection.
Reflection in Java.
Classes and Interfaces for Reflection.
Since Java 1.2
– java.lang.Object
– java.lang.Class
– java.lang.reflect.Member
– java.lang.reflect.Field (Member)
– java.lang.reflect.Method (Member)
– java.lang.reflect.Constructor (Member)
– boolean.class, char.class, int.class, double.class, ...
Java 1.0
Class
Object
Java 1.1
Field
Method
Constructor
Java 1.2
AccessibleObject
ReflectPermission
History of
Reflection in Java
43
Object
Class Point
Field
Method
Constructor
Member
SINF2335:Prog.Paradigms:
Theory,Pract.andApplic.
Reflection in Java.
Java Reflection API (Package java.lang.reflect)
Call Stack Introspection.
Introduction.
The Java’s Class Model.
Java’s Limitations on Reflection.
Reflection in Java.
Classes and Interfaces for Reflection.
Since Java 1.2
– java.lang.Object
– java.lang.Class
– java.lang.reflect.Member
– java.lang.reflect.Field (Member)
– java.lang.reflect.Method (Member)
– java.lang.reflect.Constructor (Member)
– boolean.class, char.class, int.class, double.class, ...
Java 1.0
Class
Object
Java 1.1
Field
Method
Constructor
Java 1.2
AccessibleObject
ReflectPermission
History of
Reflection in Java
44
SINF2335:Prog.Paradigms:
Theory,Pract.andApplic.
Reflective features since 1.2
■ AccessibleObject
– base class for Field, Method and Constructor objects
– setting the accessible flag in a reflected object suppresses default
Java language access control checks when it is used
• permits sophisticated applications with sufficient privilege, such as Java
Object Serialization or other persistence mechanisms, to manipulate
reflected objects in a manner that would normally be prohibited
■ ReflectPermission
– is the security permission class for reflective operations
– defines the suppressAccessChecks permission name which allows
suppressing the standard Java language access checks (for public,
default (package) access, protected, and private members)
performed by reflected objects at their point of use
45
SINF2335:Prog.Paradigms:
Theory,Pract.andApplic.
Reflection in Java.
Java Reflection API (Package java.lang.reflect)
Call Stack Introspection.
Introduction.
The Java’s Class Model.
Java’s Limitations on Reflection.
Reflection in Java.
Classes and Interfaces for Reflection.
Since Java 1.3
– java.lang.Object
– java.lang.Class
– java.lang.reflect.Member
– java.lang.reflect.AccessibleObject
– java.lang.reflect.Field (Member)
– java.lang.reflect.Method (Member)
– java.lang.reflect.Constructor (Member)
– java.lang.reflect.Proxy
– java.lang.reflect.InvocationHandler
– boolean.class, char.class, int.class, double.class, ...
Java 1.0
Class
Object
Java 1.1
Field
Method
Constructor
Java 1.2
AccessibleObject
ReflectPermission
Java 1.3
Proxy
InvocationHandler
History of
Reflection in Java
46
SINF2335:Prog.Paradigms:
Theory,Pract.andApplic.
Reflective features since 1.3
■ Proxy (class)
– provides static methods for creating dynamic proxy
classes and instances
– is superclass of all dynamic proxy classes created by
those methods
■ InvocationHandler (interface)
– is the interface implemented by the invocation handler of
a proxy instance
– each proxy instance has an associated invocation handler
– when a method is invoked on a proxy instance, the
method invocation is encoded and dispatched to the
invoke method of its invocation handler
47
SINF2335:Prog.Paradigms:
Theory,Pract.andApplic.
Reflection in Java.
Java Reflection API (Package java.lang.reflect)
Call Stack Introspection.
Introduction.
The Java’s Class Model.
Java’s Limitations on Reflection.
Reflection in Java.
Classes and Interfaces for Reflection.
Since Java 1.5
– java.lang.Object
– java.lang.Class
– java.lang.reflect.Member
– java.lang.reflect.AccessibleObject
– java.lang.reflect.Field (Member)
– java.lang.reflect.Method (Member)
– java.lang.reflect.Constructor (Member)
– java.lang.reflect.Proxy
– java.lang.reflect.InvocationHandler
– java.lang.annotation.Annotation
– java.lang.instrument.Instrumentation
– boolean.class, char.class, int.class, double.class, ...
Java 1.0
Class
Object
Java 1.1
Field
Method
Constructor
Java 1.2
AccessibleObject
ReflectPermission
Java 1.3
Proxy
InvocationHandler
Java 1.4 Java 1.5
Annotation
Instrumentation
History of
Reflection in Java
48
SINF2335:Prog.Paradigms:
Theory,Pract.andApplic.
Reflective features since 1.5
■ Annotation
– Java 1.5 supports annotating Java programs with custom annotations
– Annotations can be accessed at compile-time and at run-time
– E.g., annotate some methods with @prelog annotation and check for this
annotation to print a log message before execution of those methods
■ Instrumentation
– java.lang.instrument provides services that allow Java programming agents to
instrument programs running on the JVM
– The instrumentation mechanism is modification of the byte-codes of
methods.
■ Type
– reflection API of Java 1.5 was extended to deal with new Java 1.5 types
• generic arrays, parameterized types, type variables, ...
– Type is the common superinterface for all Java types
• several subinterfaces for the new Java 1.5 types 49

More Related Content

PDF
Advanced Reflection in Java
PPTX
Memory Management in the Java Virtual Machine(Garbage collection)
PDF
Making The Move To Java 17 (JConf 2022)
ODP
Xke spring boot
PDF
Spring Boot
PDF
Gradle - the Enterprise Automation Tool
PPTX
Spring Boot
PPTX
Introduction to Spring Boot
Advanced Reflection in Java
Memory Management in the Java Virtual Machine(Garbage collection)
Making The Move To Java 17 (JConf 2022)
Xke spring boot
Spring Boot
Gradle - the Enterprise Automation Tool
Spring Boot
Introduction to Spring Boot

What's hot (20)

PDF
Introduction to Spring Boot!
PDF
Spring boot
PDF
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
PDF
Spring boot introduction
PDF
Spring Data JPA
PPTX
Spring boot - an introduction
PPT
Spring Boot in Action
PPTX
Introduction to GraalVM
PPTX
Apache tomcat
PDF
Spring boot jpa
PPSX
Spring - Part 1 - IoC, Di and Beans
PPTX
Spring boot
PPTX
Introduction to java 8 stream api
PPTX
Spring data jpa
PPTX
Spring Boot Tutorial
PPTX
Spring boot
PPTX
JVM++: The Graal VM
PPTX
Exploring the power of Gradle in android studio - Basics & Beyond
PDF
Graal and Truffle: One VM to Rule Them All
PDF
Spring Boot
Introduction to Spring Boot!
Spring boot
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Spring boot introduction
Spring Data JPA
Spring boot - an introduction
Spring Boot in Action
Introduction to GraalVM
Apache tomcat
Spring boot jpa
Spring - Part 1 - IoC, Di and Beans
Spring boot
Introduction to java 8 stream api
Spring data jpa
Spring Boot Tutorial
Spring boot
JVM++: The Graal VM
Exploring the power of Gradle in android studio - Basics & Beyond
Graal and Truffle: One VM to Rule Them All
Spring Boot
Ad

Viewers also liked (20)

PPT
Reflection in java
ODP
Supercharging reflective libraries with InvokeDynamic
PDF
Java reflection
PPTX
Reflection in Java
PDF
Java Reflection Explained Simply
KEY
Using Chef for Automated Infrastructure in the Cloud
PDF
Docker Introduction
PDF
Ansible - Introduction
PDF
Chef Fundamentals Training Series Module 1: Overview of Chef
PDF
Overview of Chef - Fundamentals Webinar Series Part 1
PDF
Introduction to Chef: Automate Your Infrastructure by Modeling It In Code
PPTX
Jenkins and Chef: Infrastructure CI and Automated Deployment
PPT
Ansible presentation
KEY
Infrastructure Automation with Chef
PDF
DevOps and Chef
PPTX
Automated Deployments with Ansible
PPTX
Ansible: How to Get More Sleep and Require Less Coffee
PPTX
Docker introduction
PDF
Ansible tips & tricks
PDF
Ansible Introduction
Reflection in java
Supercharging reflective libraries with InvokeDynamic
Java reflection
Reflection in Java
Java Reflection Explained Simply
Using Chef for Automated Infrastructure in the Cloud
Docker Introduction
Ansible - Introduction
Chef Fundamentals Training Series Module 1: Overview of Chef
Overview of Chef - Fundamentals Webinar Series Part 1
Introduction to Chef: Automate Your Infrastructure by Modeling It In Code
Jenkins and Chef: Infrastructure CI and Automated Deployment
Ansible presentation
Infrastructure Automation with Chef
DevOps and Chef
Automated Deployments with Ansible
Ansible: How to Get More Sleep and Require Less Coffee
Docker introduction
Ansible tips & tricks
Ansible Introduction
Ad

Similar to Basics of reflection in java (20)

PPTX
Java Reflection Concept and Working
ODP
Static Analysis in IDEA
PDF
Understanding And Using Reflection
PPT
Java 5 Features
PPTX
Cuối cùng cũng đã chuẩn bị slide xong cho seminar ngày mai. Mai seminar đầu t...
PDF
Java Reflection
PDF
Basics of reflection
PPT
Reflection
PPT
Java Generics.ppt
PPTX
javaimplementation
DOCX
Java programs
PPTX
Software engineering: design for reuse
PDF
On Reflection in OO Programming Languages (v1.5.2, 14/04/14)
PPTX
L04 Software Design 2
PDF
130102 venera arnaoudova - a new family of software anti-patterns linguisti...
PPT
Java Tutorials
PPT
Object and Classes in Java
PDF
Applied Design Patterns - A Compiler Case Study
PPT
10-design-patterns1.ppt.software engineering
PDF
Metaprograms and metadata (as part of the the PTT lecture)
Java Reflection Concept and Working
Static Analysis in IDEA
Understanding And Using Reflection
Java 5 Features
Cuối cùng cũng đã chuẩn bị slide xong cho seminar ngày mai. Mai seminar đầu t...
Java Reflection
Basics of reflection
Reflection
Java Generics.ppt
javaimplementation
Java programs
Software engineering: design for reuse
On Reflection in OO Programming Languages (v1.5.2, 14/04/14)
L04 Software Design 2
130102 venera arnaoudova - a new family of software anti-patterns linguisti...
Java Tutorials
Object and Classes in Java
Applied Design Patterns - A Compiler Case Study
10-design-patterns1.ppt.software engineering
Metaprograms and metadata (as part of the the PTT lecture)

More from kim.mens (20)

PDF
Software Maintenance and Evolution
PDF
Context-Oriented Programming
PDF
Software Reuse and Object-Oriented Programming
PDF
Bad Code Smells
PDF
Object-Oriented Design Heuristics
PDF
Software Patterns
PDF
Code Refactoring
PDF
Domain Modelling
PDF
Object-Oriented Application Frameworks
PDF
Towards a Context-Oriented Software Implementation Framework
PDF
Towards a Taxonomy of Context-Aware Software Variabilty Approaches
PDF
Breaking the Walls: A Unified Vision on Context-Oriented Software Engineering
PDF
Context-oriented programming
PDF
Reflection in Ruby
PDF
Introduction to Ruby
PDF
Introduction to Smalltalk
PDF
A gentle introduction to reflection
PDF
Managing the Evolution of Information Systems with Intensional Views and Rela...
PDF
Usage contracts (presented at SATToSE 2014 in L'Aquila, Italy)
PDF
Usage contracts in a nutshell
Software Maintenance and Evolution
Context-Oriented Programming
Software Reuse and Object-Oriented Programming
Bad Code Smells
Object-Oriented Design Heuristics
Software Patterns
Code Refactoring
Domain Modelling
Object-Oriented Application Frameworks
Towards a Context-Oriented Software Implementation Framework
Towards a Taxonomy of Context-Aware Software Variabilty Approaches
Breaking the Walls: A Unified Vision on Context-Oriented Software Engineering
Context-oriented programming
Reflection in Ruby
Introduction to Ruby
Introduction to Smalltalk
A gentle introduction to reflection
Managing the Evolution of Information Systems with Intensional Views and Rela...
Usage contracts (presented at SATToSE 2014 in L'Aquila, Italy)
Usage contracts in a nutshell

Recently uploaded (20)

PPT
The World of Physical Science, • Labs: Safety Simulation, Measurement Practice
PPT
protein biochemistry.ppt for university classes
PDF
HPLC-PPT.docx high performance liquid chromatography
PPTX
INTRODUCTION TO EVS | Concept of sustainability
PPTX
BIOMOLECULES PPT........................
PDF
lecture 2026 of Sjogren's syndrome l .pdf
PPTX
Comparative Structure of Integument in Vertebrates.pptx
PPTX
famous lake in india and its disturibution and importance
PDF
CAPERS-LRD-z9:AGas-enshroudedLittleRedDotHostingaBroad-lineActive GalacticNuc...
PPTX
DRUG THERAPY FOR SHOCK gjjjgfhhhhh.pptx.
PPTX
2. Earth - The Living Planet earth and life
DOCX
Q1_LE_Mathematics 8_Lesson 5_Week 5.docx
PPTX
Derivatives of integument scales, beaks, horns,.pptx
PPTX
Vitamins & Minerals: Complete Guide to Functions, Food Sources, Deficiency Si...
PPTX
ANEMIA WITH LEUKOPENIA MDS 07_25.pptx htggtftgt fredrctvg
PDF
The scientific heritage No 166 (166) (2025)
PPTX
ognitive-behavioral therapy, mindfulness-based approaches, coping skills trai...
PPTX
neck nodes and dissection types and lymph nodes levels
PDF
ELS_Q1_Module-11_Formation-of-Rock-Layers_v2.pdf
PDF
IFIT3 RNA-binding activity primores influenza A viruz infection and translati...
The World of Physical Science, • Labs: Safety Simulation, Measurement Practice
protein biochemistry.ppt for university classes
HPLC-PPT.docx high performance liquid chromatography
INTRODUCTION TO EVS | Concept of sustainability
BIOMOLECULES PPT........................
lecture 2026 of Sjogren's syndrome l .pdf
Comparative Structure of Integument in Vertebrates.pptx
famous lake in india and its disturibution and importance
CAPERS-LRD-z9:AGas-enshroudedLittleRedDotHostingaBroad-lineActive GalacticNuc...
DRUG THERAPY FOR SHOCK gjjjgfhhhhh.pptx.
2. Earth - The Living Planet earth and life
Q1_LE_Mathematics 8_Lesson 5_Week 5.docx
Derivatives of integument scales, beaks, horns,.pptx
Vitamins & Minerals: Complete Guide to Functions, Food Sources, Deficiency Si...
ANEMIA WITH LEUKOPENIA MDS 07_25.pptx htggtftgt fredrctvg
The scientific heritage No 166 (166) (2025)
ognitive-behavioral therapy, mindfulness-based approaches, coping skills trai...
neck nodes and dissection types and lymph nodes levels
ELS_Q1_Module-11_Formation-of-Rock-Layers_v2.pdf
IFIT3 RNA-binding activity primores influenza A viruz infection and translati...

Basics of reflection in java

  • 1. SINF2335:Prog.Paradigms: Theory,Pract.andApplic. Lecture 9 :
 Basics of Reflection in Java LSINF 2335 Programming Paradigms Prof. Kim Mens UCL / EPL / INGI (Slides partly based on the
 book “Java Reflection in Action”, on The Java Tutorials, and on
 slides by Pr. Walter Cazzola)
  • 2. SINF2335:Prog.Paradigms: Theory,Pract.andApplic. Some References 2 Ira R. Forman Nate Forman M A N N I N G Sample Chapter
  • 3. SINF2335:Prog.Paradigms: Theory,Pract.andApplic. Basics of Reflection in Java ■ About reflection in Java ■ Example of a reflective Java program ■ The Java meta-object protocol ■ The Java reflection API – Class – Field, Method and Constructor ■ Metaclass madness ■ Java's dynamic proxies ■ Reflective features in Java 1.5 3
  • 4. SINF2335:Prog.Paradigms: Theory,Pract.andApplic. Basics of Reflection in Java ■ About reflection in Java ■ Example of a reflective Java program ■ The Java meta-object protocol ■ The Java reflection API – Class – Field, Method and Constructor ■ History of reflection in Java 4
  • 5. SINF2335:Prog.Paradigms: Theory,Pract.andApplic. Reflection, reification, introspection & intercession ■ (Computational) reflection: ability of a running program to inspect and change itself. ■ Reification: making the language concepts (meta- level) accessible (at base level) to the program, so that they can be manipulated as ordinary data. ■ Introspection: self-examination; only looking at the reified entities. ■ Intercession: when you actually intervene in the program execution as well (by manipulating those reified entities) 5
  • 6. SINF2335:Prog.Paradigms: Theory,Pract.andApplic. 6 About Reflection in Java ■ Java provides an API for reflection – a rich set of operations for introspection – few intercession capabilities ■ Can be used to examine or modify the runtime behaviour of applications running in the JVM ■ Warning – is a pretty advanced feature • should be used only by developers who have a strong grasp of the fundamentals of the language – when to avoid it • in performance-sensitive applications • in security-related code • may expose some internals (e.g. accessing of private fields)
  • 7. SINF2335:Prog.Paradigms: Theory,Pract.andApplic. Basics of Reflection in Java ■ About reflection in Java ■ Example of a reflective Java program ■ The Java meta-object protocol ■ The Java reflection API – Class – Field, Method and Constructor ■ History of reflection in Java 7
  • 8. SINF2335:Prog.Paradigms: Theory,Pract.andApplic. An Illustrative Example 8 (Taken from Chapter 1 of the book “Java Reflection in Action” by Forman & Forman.) ■ User interface implementation ■ Contains several visual components (classes) – some developed in-house – some open source – some belong the standard Java libraries – some are bought ■ All these components understand – setColor(Color aColor) ■ Problem: how to invoke this method? – the components share no common supertype of interface – only common base class is Object
  • 9. SINF2335:Prog.Paradigms: Theory,Pract.andApplic. public class Component4 { Color myColor; public void setColor(Color color) { myColor = color; } ... } public class Component3 { Color myColor; public void setColor(Color color) { myColor = color; } ... } An Illustrative Example 9 public class Component1 { Color myColor; public void setColor(Color color) { myColor = color; } ... } public class Component2 { Color myColor; public void setColor(Color color) { myColor = color; } ... }
  • 10. SINF2335:Prog.Paradigms: Theory,Pract.andApplic. What’s the problem? 10 public class Main { static Object[] components = new Object[10]; static Color color = new Color(0); public static void initializeComponents() { components[0] = new Component1(); components[1] = new Component2(); ... } public static void main(String[] args) { initializeComponents(); for (int i = 0; i < args.length; i++) if (components[i] != null) components[i].setColor(color); } } The method setColor(color) is undefined for the type Object
  • 11. SINF2335:Prog.Paradigms: Theory,Pract.andApplic. Possible solutions? 11 ■ Define setColor on Object – not a nice solution; not possible anyway ■ Use a typecast – impossible: Object is the only common supertype ■ Make components implement common interface – would work : we can use that interface as common type – unfortunately some code is not ours: cannot be changed ■ Use an adapter for each component – i.e. a “fake” component that delegates to the real one – all adapters implement a common interface – works, but explosion of extra classes and objects
  • 12. SINF2335:Prog.Paradigms: Theory,Pract.andApplic. More solutions? 12 ■ Use instanceOf and casting if (components[i] instanceof Component1) ((Component1) components[i]).setColor(color); if (components[i] instanceof Component2) ((Component2) components[i]).setColor(color); ... – works, but code bloated with conditionals and calls – and concrete types hard-coded in the code ■ Why not use reflection? – to find the right setColor method to call – and invoke it using reflection
  • 13. SINF2335:Prog.Paradigms: Theory,Pract.andApplic. Reflective solution 13 public class Main { static Object[] components = new Object[10]; static Color color = new Color(0); public static void initializeComponents() { components[0] = new Component1(); components[1] = new Component2(); ... } public static void main(String[] args) { initializeComponents(); for (int i = 0; i < args.length; i++) if (components[i] != null) setObjectColor(components[i],color); } ... } Reflective method
  • 14. SINF2335:Prog.Paradigms: Theory,Pract.andApplic. Reflective solution 14 public static void setObjectColor( Object obj, Color color ) {
 Class cls = obj.getClass(); try { Method method = cls.getMethod( "setColor", new Class[] {Color.class} ); method.invoke( obj, new Object[] {color} ); } catch (NoSuchMethodException ex) { throw new IllegalArgumentException( cls.getName() + " does not support method setColor(Color)" ); } catch (IllegalAccessException ex) { throw new IllegalArgumentException( "Insufficient access permissions to call" + "setColor(:Color) in class " + cls.getName()); } catch (InvocationTargetException ex) { throw new RuntimeException(ex); } }
  • 15. SINF2335:Prog.Paradigms: Theory,Pract.andApplic. Reflective solution 15 public static void setObjectColor( Object obj, Color color ) { Class cls = obj.getClass(); try { Method method = cls.getMethod( "setColor", new Class[] {Color.class} ); method.invoke( obj, new Object[] {color} ); } catch (NoSuchMethodException ex) { throw new IllegalArgumentException( cls.getName() + " does not support method setColor(Color)" ); } catch (IllegalAccessException ex) { throw new IllegalArgumentException( "Insufficient access permissions to call" + "setColor(:Color) in class " + cls.getName()); } catch (InvocationTargetException ex) { throw new RuntimeException(ex); } } Query obj for its class
  • 16. SINF2335:Prog.Paradigms: Theory,Pract.andApplic. Reflective solution 16 public static void setObjectColor( Object obj, Color color ) { Class cls = obj.getClass(); try { Method method = cls.getMethod( "setColor", new Class[] {Color.class} ); method.invoke( obj, new Object[] {color} ); } catch (NoSuchMethodException ex) { throw new IllegalArgumentException( cls.getName() + " does not support method setColor(Color)" ); } catch (IllegalAccessException ex) { throw new IllegalArgumentException( "Insufficient access permissions to call" + "setColor(:Color) in class " + cls.getName()); } catch (InvocationTargetException ex) { throw new RuntimeException(ex); } } Query class object for setColor method
  • 17. SINF2335:Prog.Paradigms: Theory,Pract.andApplic. Reflective solution 17 public static void setObjectColor( Object obj, Color color ) { Class cls = obj.getClass(); try { Method method = cls.getMethod( "setColor", new Class[] {Color.class} ); method.invoke( obj, new Object[] {color} ); } catch (NoSuchMethodException ex) { throw new IllegalArgumentException( cls.getName() + " does not support method setColor(Color)" ); } catch (IllegalAccessException ex) { throw new IllegalArgumentException( "Insufficient access permissions to call" + "setColor(:Color) in class " + cls.getName()); } catch (InvocationTargetException ex) { throw new RuntimeException(ex); } } Call resulting method on target obj
  • 18. SINF2335:Prog.Paradigms: Theory,Pract.andApplic. Reflective solution 18 public static void setObjectColor( Object obj, Color color ) { Class cls = obj.getClass(); try { Method method = cls.getMethod( "setColor", new Class[] {Color.class} ); method.invoke( obj, new Object[] {color} ); } catch (NoSuchMethodException ex) { throw new IllegalArgumentException( cls.getName() + " does not support method setColor(Color)" ); } catch (IllegalAccessException ex) { throw new IllegalArgumentException( "Insufficient access permissions to call" + "setColor(:Color) in class " + cls.getName()); } catch (InvocationTargetException ex) { throw new RuntimeException(ex); } } Catch error if class obj does not support setColor method
  • 19. SINF2335:Prog.Paradigms: Theory,Pract.andApplic. Reflective solution 19 public static void setObjectColor( Object obj, Color color ) { Class cls = obj.getClass(); try { Method method = cls.getMethod( "setColor", new Class[] {Color.class} ); method.invoke( obj, new Object[] {color} ); } catch (NoSuchMethodException ex) { throw new IllegalArgumentException( cls.getName() + " does not support method setColor(Color)" ); } catch (IllegalAccessException ex) { throw new IllegalArgumentException( "Insufficient access permissions to call" + "setColor(:Color) in class " + cls.getName()); } catch (InvocationTargetException ex) { throw new RuntimeException(ex); } } Catch error if invoker cannot call setColor method
  • 20. SINF2335:Prog.Paradigms: Theory,Pract.andApplic. Reflective solution 20 public static void setObjectColor( Object obj, Color color ) { Class cls = obj.getClass(); try { Method method = cls.getMethod( "setColor", new Class[] {Color.class} ); method.invoke( obj, new Object[] {color} ); } catch (NoSuchMethodException ex) { throw new IllegalArgumentException( cls.getName() + " does not support method setColor(Color)" ); } catch (IllegalAccessException ex) { throw new IllegalArgumentException( "Insufficient access permissions to call" + "setColor(:Color) in class " + cls.getName()); } catch (InvocationTargetException ex) { throw new RuntimeException(ex); } } Catch error if method setColor throws exception
  • 21. SINF2335:Prog.Paradigms: Theory,Pract.andApplic. An Illustrative Example 21 ■ Introspection – query object for its class – query class for its methods ■ Dynamic invocation – dynamically call method at run-time
 without specifying which one at compile-time ■ Care should be taken to handle all exceptions ■ This solution is – flexible and elegant – though somewhat verbose – but has some performance penalties
  • 22. SINF2335:Prog.Paradigms: Theory,Pract.andApplic. Basics of Reflection in Java ■ About reflection in Java ■ Example of a reflective Java program ■ The Java meta-object protocol ■ The Java reflection API – Class – Field, Method and Constructor ■ History of reflection in Java 22
  • 23. SINF2335:Prog.Paradigms: Theory,Pract.andApplic. The Java Meta-Object Protocol 23 Point aPoint = new Point(2,3)
 aPoint.getClass() ➡ class Point Class aClass = aPoint.getClass()
 aClass.getClass() ➡ class java.lang.Class Class aMeta = aClass.getClass()
 aMeta.getClass() ➡ class java.lang.Class Class aMetaMeta = aMeta.getClass()
 aMetaMeta.getClass() ➡ class java.lang.Class Point aPoint getClass() Class getClass() getClass()
  • 24. SINF2335:Prog.Paradigms: Theory,Pract.andApplic. ■ Objects are instances of a class ■ Classes are instances of the meta class Class ■ The meta class Class is an instance of itself Class Metaclass ObjectObjectObjectObjectObject Point Class ObjectObjectObjectObjectaPoint The metaclass loop in Java instance of
  • 25. SINF2335:Prog.Paradigms: Theory,Pract.andApplic. The Java Meta-Object Protocol Object Class Point instance of subclass of Field Method Constructor Member implements interface
  • 26. SINF2335:Prog.Paradigms: Theory,Pract.andApplic. Basics of Reflection in Java ■ About reflection in Java ■ Example of a reflective Java program ■ The Java meta-object protocol ■ The Java reflection API – Class – Field, Method and Constructor ■ History of reflection in Java 26
  • 27. SINF2335:Prog.Paradigms: Theory,Pract.andApplic. The Java Reflection API ■ The Java Core Reflection API – provides a small, type-safe, and secure API – that supports introspection about the classes and objects in the current JVM – If permitted by security policy, the API 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 – Intercession on classes and objects is forbidden
 27
  • 28. SINF2335:Prog.Paradigms: Theory,Pract.andApplic. The Java Reflection API ■ java.lang.reflect is in a subpackage of java.lang ■ Defines the following classes and methods: – The classes Field, Method and Constructor • reflect class and interface members and constructors • provide reflective information about the underlying member or constructor • a type-safe means to use the member or constructor to operate on Java objects – Methods of class Class that enable the construction of new instances of the Field, Method and Constructor classes. – and more... ■ There are also some parts of the java.lang package that support reflection – In particular the class Class 28
  • 29. SINF2335:Prog.Paradigms: Theory,Pract.andApplic. Basics of Reflection in Java ■ About reflection in Java ■ Example of a reflective Java program ■ The Java meta-object protocol ■ The Java reflection API – Class – Field, Method and Constructor ■ History of reflection in Java 29
  • 30. SINF2335:Prog.Paradigms: Theory,Pract.andApplic. Class ■ Instances of the class Class represent classes and interfaces in a running Java application. – Every array also belongs to a class that is reflected as a Class object • shared by all arrays with same element type and dimension – Primitive Java types (boolean, byte, char, int, ...), and void are also represented as Class objects ■ Class has no public constructor – Class objects are constructed automatically by the Java Virtual Machine as classes are loaded – and by calls to defineClass method in the class loader ■ Defined in java.lang (instead of java.lang.reflect) 30
  • 31. SINF2335:Prog.Paradigms: Theory,Pract.andApplic. Using Class: examples ■ Using a Class object to print the class name of an object: void printClassName(Object obj) { System.out.println("The class of " + obj + " is " + obj.getClass().getName()); } ■ Getting the Class object for a named type using a class literal: System.out.println("The name of class Foo is:" + Foo.class.getName()); 31
  • 32. SINF2335:Prog.Paradigms: Theory,Pract.andApplic. Class: querying for methods 32 knows that setObjectColor always wants a method that takes one Color argument. He specifies this using Color.class. Class has other methods for introspecting about methods. The signatures and return types for these methods are shown in table 1.1. As in the previous example, the queries use an array of Class to indicate the types of the parameters. In Table 1.1 The methods defined by Class for method query Method Description Method getMethod( String name, Class[] parameterTypes ) Returns a Method object that represents a public method (either declared or inherited) of the target Class object with the signature specified by the second parameters Method[] getMethods() Returns an array of Method objects that represent all of the public methods (either declared or inher- ited) supported by the target Class object Method getDeclaredMethod( String name, Class[] parameterTypes ) Returns a Method object that represents a declared method of the target Class object with the signature specified by the second parameters Method[] getDeclaredMethods() Returns an array of Method objects that represent all of the methods declared by the target Class object + getConstructor, getField, ...
  • 33. SINF2335:Prog.Paradigms: Theory,Pract.andApplic. Class: dealing with type representation 33 Representing types with class objects Java represents primitive, array, and interface types by introducing class objects represent them. These class objects cannot do everything that many other cl objects can. For instance, you cannot create a new instance of a primitive or int Table 1.2 Methods defined by Class that deal with type representation Method Description String getName() Returns the fully qualified name of the target Class object Class getComponentType() If the target object is a Class object for an array, returns the Class object representing the component type boolean isArray() Returns true if and only if the target Class object repre- sents an array boolean isInterface() Returns true if and only if the target Class object repre- sents an interface boolean isPrimitive() Returns true if and only if the target Class object repre- sents a primitive type or void
  • 34. SINF2335:Prog.Paradigms: Theory,Pract.andApplic. Basics of Reflection in Java ■ About reflection in Java ■ Example of a reflective Java program ■ The Java meta-object protocol ■ The Java reflection API – Class – Field, Method and Constructor ■ History of reflection in Java 34
  • 35. SINF2335:Prog.Paradigms: Theory,Pract.andApplic. Field, Method and Constructor ■ Three classes to reason about Java members ■ Only JVM may create instances of these classes – i.e., they are final ■ Can be used to manipulate the underlying objects – get reflective information about the underlying member – get and set field values – invoke methods on objects or classes – create new instances of classes ■ These classes all implement the Member interface – defines methods to query member for basic information: • the class implementing a member • the Java language modifiers for the member 35
  • 36. SINF2335:Prog.Paradigms: Theory,Pract.andApplic. Field ■ A Field object represents a reified field – may be a class variable (a static field) – or an instance variable (a non-static field) ■ Methods of class Field are used to – obtain the type of the field – get and set the field’s value on objects 36
  • 37. SINF2335:Prog.Paradigms: Theory,Pract.andApplic. Field 37 Method Description getDeclaringClass() Returns the Class object representing the class or interface that declares the field represented by this Field object. getModifiers() Returns the Java language modifiers for the field represented by this Field object, as an integer. getName() Returns the name of the field represented by this Field object, as String. getType() Returns a Class object that identifies the declared type for the field represented by this Field object. get(Object obj) Returns the value of the field represented by this Field object, on the specified object. The value is automatically wrapped in an object if it has a primitive type. set(Object obj, Object value) Sets the field represented by this Field object on the specified object argument to the specified new value. The new value is automatically unwrapped if the underlying field has a primitive type. toString() Returns a String describing this Field.
  • 38. SINF2335:Prog.Paradigms: Theory,Pract.andApplic. Constructor ■ A Constructor object represents a reified constructor ■ Methods of class Constructor are used to – obtain the formal parameter types of the constructor – get the checked exception types of the constructor – create and initialise new instances of the class that declares the constructor • provided the class is instantiable • using the method newInstance 38
  • 39. SINF2335:Prog.Paradigms: Theory,Pract.andApplic. Constructor 39 Method Description getDeclaringClass() Returns the Class object representing the class that declares the constructor represented by this Constructor object. getExceptionTypes() Returns an array of Class objects that represent the types of of exceptions declared to be thrown by the underlying constructor represented by this Constructor object. getModifiers() Returns the Java language modifiers for the constructor represented by this Constructor object, as an integer. getName() Returns the name of this constructor, as a string. getParameterTypes() Returns an array of Class objects that represent the formal parameter types, in declaration order, of the constructor represented by this Constructor object. newInstance(Object[] initargs) Uses the constructor represented by this Constructor object to create and initialize a new instance of the constructor's declaring class, with the specified initialization parameters. toString() Returns a String describing this Constructor.
  • 40. SINF2335:Prog.Paradigms: Theory,Pract.andApplic. Method ■ A Method object represents a reified method – may be an abstract method, an instance method or a class (static) method ■ Methods of class Method are used to – obtain the formal parameter types of the method – obtain its return type – get the checked exception types of the method – invoke the method on target objects • instance and abstract method invocation uses dynamic method resolution – based on target object’s run-time class • static method invocation uses the static method of the method’s declaring class 40
  • 41. SINF2335:Prog.Paradigms: Theory,Pract.andApplic. Method 41 Understanding method objects 15 metaobjects that represent methods. Table 1.3 shows some of the methods sup- Table 1.3 Methods defined by Method Method Description Class getDeclaringClass() Returns the Class object that declared the method repre- sented by this Method object Class[] getExceptionTypes() Returns an array of Class objects representing the types of the exceptions declared to be thrown by the method repre- sented by this Method object int getModifiers() Returns the modifiers for the method represented by this Method object encoded as an int String getName() Returns the name of the method represented by this Method object Class[] getParameterTypes() Returns an array of Class objects representing the formal parameters in the order in which they were declared Class getReturnType() Returns the Class object representing the type returned by the method represented by this Method object Object invoke(Object obj, Object[] args) Invokes the method represented by this Method object on the specified object with the arguments specified in the Object array
  • 42. SINF2335:Prog.Paradigms: Theory,Pract.andApplic. Basics of Reflection in Java ■ About reflection in Java ■ Example of a reflective Java program ■ The Java meta-object protocol ■ The Java reflection API – Class – Field, Method and Constructor ■ History of reflection in Java 42
  • 43. SINF2335:Prog.Paradigms: Theory,Pract.andApplic. Reflection in Java. Java Reflection API (Package java.lang.reflect) Call Stack Introspection. Introduction. The Java’s Class Model. Java’s Limitations on Reflection. Reflection in Java. Classes and Interfaces for Reflection. Since Java 1.2 – java.lang.Object – java.lang.Class – java.lang.reflect.Member – java.lang.reflect.Field (Member) – java.lang.reflect.Method (Member) – java.lang.reflect.Constructor (Member) – boolean.class, char.class, int.class, double.class, ... Java 1.0 Class Object Java 1.1 Field Method Constructor Java 1.2 AccessibleObject ReflectPermission History of Reflection in Java 43 Object Class Point Field Method Constructor Member
  • 44. SINF2335:Prog.Paradigms: Theory,Pract.andApplic. Reflection in Java. Java Reflection API (Package java.lang.reflect) Call Stack Introspection. Introduction. The Java’s Class Model. Java’s Limitations on Reflection. Reflection in Java. Classes and Interfaces for Reflection. Since Java 1.2 – java.lang.Object – java.lang.Class – java.lang.reflect.Member – java.lang.reflect.Field (Member) – java.lang.reflect.Method (Member) – java.lang.reflect.Constructor (Member) – boolean.class, char.class, int.class, double.class, ... Java 1.0 Class Object Java 1.1 Field Method Constructor Java 1.2 AccessibleObject ReflectPermission History of Reflection in Java 44
  • 45. SINF2335:Prog.Paradigms: Theory,Pract.andApplic. Reflective features since 1.2 ■ AccessibleObject – base class for Field, Method and Constructor objects – setting the accessible flag in a reflected object suppresses default Java language access control checks when it is used • permits sophisticated applications with sufficient privilege, such as Java Object Serialization or other persistence mechanisms, to manipulate reflected objects in a manner that would normally be prohibited ■ ReflectPermission – is the security permission class for reflective operations – defines the suppressAccessChecks permission name which allows suppressing the standard Java language access checks (for public, default (package) access, protected, and private members) performed by reflected objects at their point of use 45
  • 46. SINF2335:Prog.Paradigms: Theory,Pract.andApplic. Reflection in Java. Java Reflection API (Package java.lang.reflect) Call Stack Introspection. Introduction. The Java’s Class Model. Java’s Limitations on Reflection. Reflection in Java. Classes and Interfaces for Reflection. Since Java 1.3 – java.lang.Object – java.lang.Class – java.lang.reflect.Member – java.lang.reflect.AccessibleObject – java.lang.reflect.Field (Member) – java.lang.reflect.Method (Member) – java.lang.reflect.Constructor (Member) – java.lang.reflect.Proxy – java.lang.reflect.InvocationHandler – boolean.class, char.class, int.class, double.class, ... Java 1.0 Class Object Java 1.1 Field Method Constructor Java 1.2 AccessibleObject ReflectPermission Java 1.3 Proxy InvocationHandler History of Reflection in Java 46
  • 47. SINF2335:Prog.Paradigms: Theory,Pract.andApplic. Reflective features since 1.3 ■ Proxy (class) – provides static methods for creating dynamic proxy classes and instances – is superclass of all dynamic proxy classes created by those methods ■ InvocationHandler (interface) – is the interface implemented by the invocation handler of a proxy instance – each proxy instance has an associated invocation handler – when a method is invoked on a proxy instance, the method invocation is encoded and dispatched to the invoke method of its invocation handler 47
  • 48. SINF2335:Prog.Paradigms: Theory,Pract.andApplic. Reflection in Java. Java Reflection API (Package java.lang.reflect) Call Stack Introspection. Introduction. The Java’s Class Model. Java’s Limitations on Reflection. Reflection in Java. Classes and Interfaces for Reflection. Since Java 1.5 – java.lang.Object – java.lang.Class – java.lang.reflect.Member – java.lang.reflect.AccessibleObject – java.lang.reflect.Field (Member) – java.lang.reflect.Method (Member) – java.lang.reflect.Constructor (Member) – java.lang.reflect.Proxy – java.lang.reflect.InvocationHandler – java.lang.annotation.Annotation – java.lang.instrument.Instrumentation – boolean.class, char.class, int.class, double.class, ... Java 1.0 Class Object Java 1.1 Field Method Constructor Java 1.2 AccessibleObject ReflectPermission Java 1.3 Proxy InvocationHandler Java 1.4 Java 1.5 Annotation Instrumentation History of Reflection in Java 48
  • 49. SINF2335:Prog.Paradigms: Theory,Pract.andApplic. Reflective features since 1.5 ■ Annotation – Java 1.5 supports annotating Java programs with custom annotations – Annotations can be accessed at compile-time and at run-time – E.g., annotate some methods with @prelog annotation and check for this annotation to print a log message before execution of those methods ■ Instrumentation – java.lang.instrument provides services that allow Java programming agents to instrument programs running on the JVM – The instrumentation mechanism is modification of the byte-codes of methods. ■ Type – reflection API of Java 1.5 was extended to deal with new Java 1.5 types • generic arrays, parameterized types, type variables, ... – Type is the common superinterface for all Java types • several subinterfaces for the new Java 1.5 types 49