0% found this document useful (0 votes)
35 views

Lecture17 JavaReflection

Reflection in Java allows examination of programs and modification of their structure and behavior at runtime. It provides APIs to obtain Class objects representing metadata about classes, fields, and methods. This metadata can then be used to dynamically create instances, set field values, invoke methods, and more. Many Java frameworks like Spring heavily use reflection for tasks like dependency injection and runtime configuration.

Uploaded by

Karim Ghaddar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views

Lecture17 JavaReflection

Reflection in Java allows examination of programs and modification of their structure and behavior at runtime. It provides APIs to obtain Class objects representing metadata about classes, fields, and methods. This metadata can then be used to dynamically create instances, set field values, invoke methods, and more. Many Java frameworks like Spring heavily use reflection for tasks like dependency injection and runtime configuration.

Uploaded by

Karim Ghaddar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

Java Reflection

1
Reflection (or Introspection)
➢ Reflection is the ability to examine a program and to change its structure
and behavior at run time
➢ It is a feature present in Java, Python, and C#
➢ Many open source Java projects use reflection, such as JBoss, JUnit, Maven,
and Spring Boot.
➢ These projects use the Java Reflection API to implement critical tasks in a
program:
– handling dependencies dynamically
– inspecting program components
– manipulating fields
– invoking methods at run time

2
Classes
How to obtain a Class object and use it to examine properties of a class,
including its declaration and contents?

➢ The JVM instantiates an instance of java.lang.Class for every loaded class,


which provides methods to examine the runtime properties of the object
including its members and type information.

➢ Class also provides the ability to create new classes and objects. Most
importantly, it is the entry point for all of the Reflection APIs.

3
Classes: There are several ways to get a Class
1) Object.getClass(): If an instance of an object is available

Class c = "foo".getClass();
Returns the Class for String

byte[] bytes = new byte[1024];


Class c = bytes.getClass();
Returns the Class for an array with component type byte.

Set<String> s = new HashSet<String>();


Class c = s.getClass();
Returns the Class for java.util.HashSet.

4
Classes: There are several ways to get a Class
2) The .class syntax: If the type is available
It is possible to obtain a Class by appending ".class" to the name of the type.
boolean b; // works for primitive types also
Class c = b.getClass(); // compile-time error
Class c = boolean.getClass(); // compile-time error
Class c = boolean.class; // correct
The .class syntax returns the Class corresponding to the type boolean.

Class c = java.io.PrintStream.class;
The variable c will be the Class corresponding to the type java.io.PrintStream.

Class c = int[][][].class;

Note: Class is generic with a type parameter (Class<T>). For example if the type being modeled is a String,
then we use Class<String>, if it is unknown, we use Class<?>. The <?> is omitted in the slides for brevity, but
while coding, it is preferred to include it to avoid the warning of using a raw-type. 5
Classes: There are several ways to get a Class
3) Class.forName(): If the fully-qualified name of a class is available.

This cannot be used for primitive types.

Class c = Class.forName("com.aub.MyLocaleServiceProvider");
This statement will create a class from the given fully-qualified name.

Class cDoubleArray = Class.forName("[D");


The variable cDoubleArray will contain the Class corresponding to an array of
primitive type double (i.e., the same as double[].class).

Class cStringArray = Class.forName("[[Ljava.lang.String;");


The cStringArray variable will contain the Class corresponding to a two-
dimensional array of String (i.e., identical to String[][].class).
6
Classes: Examining Class Modifiers and Types

➢ ClassDeclarationSpy shows how to obtain the declaration components of a


class including the modifiers, generic type parameters, implemented
interfaces, and the inheritance path

ClassDeclarationSpy.java

7
Classes: Discovering Class Members
➢ The get*() methods below can be used to determine the list of all elements,
including any which are inherited

8
Fields: java.lang.reflect.Field
1) Obtaining Field Types and modifiers:
Print the field's type, generic type, and modifiers given a fully-qualified class name and
field name

2) Getting and Setting Field Values:


Given an instance of a class, it is possible to use reflection to set the values of fields in
that class (and even change their accessibility!)

See FieldSpy.java

Note: type erasure does not mean that the JDK eliminates type information at runtime;
it just does not use it. So generic types could be identified using reflection/JBE

9
Methods: java.lang.reflect.Method
➢ java.lang.reflect.Method provides APIs to access information about a
method's modifiers, return type, parameters, annotations, and thrown
exceptions. It can also be used to invoke methods
1) Obtaining Method Type Information
2) Obtaining Info of Method Parameters
3) Retrieving sing Method Modifiers

MethodSpy.java
MethodParameterSpy.java
MethodModifierSpy.java

10
Methods: Invoking Methods
➢ Finding and Invoking a Method with a Specific Declaration:
Consider a test suite which uses reflection to invoke test methods in a
given class. Invoke1.java searches for methods in a class which begin
with the string "test", have a boolean return type, and a single parameter
of type doule. It then invokes each matching method.

Invoke1.java

11
Creating New Class Instances

➢ There are two reflective methods for creating instances of classes:


java.lang.reflect.Constructor.newInstance() and Class.newInstance()

Example in Invoke1.java presented earlier.

12
Arrays
➢ Identifying Array Types
Array types may be identified by invoking Class.isArray()
ArrayFind.java identifies the fields in the named class that are of array
type and reports the component type for each of them.

➢ Creating New Arrays


CreateMatrix.java illustrates how to create and initialize a multi-
dimensional array using reflection.

13

You might also like