Java Reflection: Discovering Classes, Fields, Constructors, and Methods, Slides of Computer Engineering and Programming

An overview of java reflection, a powerful feature that allows runtime discovery of an object's class, fields, constructors, and methods. It covers various techniques for retrieving class objects, getting class names, identifying interfaces, discovering class fields, and invoking methods. The document also explains how to create objects dynamically using no-argument constructors and constructors with arguments.

Typology: Slides

2011/2012

Uploaded on 07/11/2012

dhananad
dhananad 🇮🇳

4

(4)

39 documents

1 / 22

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
Reflection
Docsity.com
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16

Partial preview of the text

Download Java Reflection: Discovering Classes, Fields, Constructors, and Methods and more Slides Computer Engineering and Programming in PDF only on Docsity!

Reflection

Reflection (Introspection)

Allows runtime discovery of an object’s

class

fields

constructors

methods

Within access restrictions, you can

get and set discovered fields

invoke discovered methods

create new objects using discovered constructors

Particularly useful for creating tools such as

debuggers and class browsers

public, protected, private protected, private

Examining Class

Class object

For each class, JRE maintains an

immutable Class object which reflects the

information about the class

Using reflection API, you can invoke

methods on a Class object which return

Constructor, Method, and Field

Retrieving Class object

invoke object.getClass

To retrieve the Class object for the superclass, invoke

the getSuperclass method

If class name is known at compile time, then use:

If the class name is unknown at compile time, but

available at runtime, then use:

Class c = mystery.getClass(); Class sc = c.getSuperclass();

Class c = java.awt.Button.class;

String className = “java.awt.Button”; Class c = Class.forName(className);

Class c = mystery.getClass();

Discovering Class Modifiers

(public/abstract/final)

Invoke

getModifiers()

on a Class object to

retrieve a set of

modifiers

Check the modifiers

by calling

isPublic(),

isAbstract(),

and isFinal()

String s = new String(); printModifiers(s); ... public static void printModifiers(Object o) {

Class c = o.getClass(); int m = c.getModifiers();

if ( Modifier.isPublic(m) ) System.out.println ("public"); if ( Modifier.isAbstract(m) ) System.out.println ("abstract"); if ( Modifier.isFinal(m) ) System.out.println ("final"); } public final

Finding Superclasses:

getSuperclass()

printSuperclasses(new Button());

static void printSuperclasses(Object o) {

Class subclass = o.getClass();

Class superclass = subclass.getSuperclass();

while (superclass != null ) {

String className = superclass.getName();

System.out.println(className);

subclass = superclass;

superclass = subclass.getSuperclass();

java.awt.Component java.lang.Object

Examining Interfaces

isInterface() checks whether a Class object represents an interface or a class getField() finds public constants of an interface ... Class observer = Observer.class; Class observable = Observable.class; verifyInterface(observer); verifyInterface(observable); ... static void verifyInterface(Class c) { String name = c.getName(); if ( c.isInterface() ) { System.out.println(name + " is an interface."); } else { System.out.println(name + " is a class."); } } (^) java.util.Observer is an interface. java.util.Observable is a class.

Identifying Class Fields

getFields() of Class object returns an array of Field

objects containing one object per accessible public field

A public field is accessible if it is a member of either:

this class

a superclass of this class

an interface implemented by this class

an interface extended from an interface implemented by this

class

The methods provided by the Field class allow you to

retrieve the field's name, type, and set of modifiers

Discovering Class Constructors:

getConsructors()

getConstructors returns an array of

Constructor objects

Methods provided by the

Constructor can be used to

determine the constructor's name, set

of modifiers, parameter types, and set

of throwable exceptions

static void showConstructors(Object o) { Class c = o.getClass(); Constructor[] constructors = c.getConstructors(); for ( int i = 0; i < constructors.length; i++) { System.out.print("( "); Class[] paramTypes = constructors[i].getParameterTypes(); for ( int k = 0; k < parameterTypes.length; k++) { String paramString = paramTypes[k].getName(); System.out.print(paramString + " "); } System.out.println(")"); } }

( ) (int int ) (int int int int) (java.awt.Dimension) (java.awt.Point) (java.awt.Dimension) (java.awt.Rectangle)

Obtaining Method Information

getMethods returns an array of Method objects

Use a Method object to uncover a method's name,

return type, parameter types, set of modifiers, and set of

throwable exceptions

The sample program performs the following tasks:

Retrieves an array of Method objects from the Class object by

calling getMethods

For every element in the Method array, the program:

  • retrieves the method name by calling getName
  • gets the return type by invoking getReturnType
  • creates an array of Class objects by invoking getParameterTypes

To retrieve the class name for every one of these parameters,

the program invokes getName against each Class object in the

array returned in the preceding step

Manipulating Objects

The simplest way to create an object is

Sometimes you may not know the class of an

object until runtime

Reflection API provides you to create an object

whose class is unknown until runtime

Creating an object dynamically depends on

whether or not the constructor you want to use

has arguments

Rectangle r = new Rectangle();

Using No-Argument Constructors

Invoke the newInstance method on a Class object to create an

object with the no-argument constructor

The newInstance method throws a NoSuchMethodException

if the class does not have a no-argument constructor

static Object createObject(String className) { Object object = null; try { Class classDefinition = Class.forName(className); object = classDefinition.newInstance(); } catch (InstantiationException e) { System.out.println(e); } catch (IllegalAccessException e) { System.out.println(e); } catch (ClassNotFoundException e) { System.out.println(e); } return object; }

Getting Field Values

This is a three-step process:

Create a Class object

Create a Field object by invoking getField on the Class

object

Invoke one of the get methods on the Field object

void printHeight(Rectangle r) { Field heightField; Integer heightValue; Class c = r.getClass();

try { heightField = c.getField ("height"); heightValue = (Integer) heightField.get(r); System.out.println ("Height: “ + heightValue.toString()); } catch (NoSuchFieldException e) { System.out.println(e); } catch (SecurityException e) { System.out.println(e); } catch (IllegalAccessException e) { System.out.println(e); }

Setting Field Value

Create a Class object Create a Field object by invoking getField on the Class object Invoke the appropriate set method on the Field object

void modifyWidth(Rectangle r, Integer widthParam){ Field widthField; Integer widthValue; Class c = r.getClass();

try { widthField = c.getField ("width"); widthField.set(r, widthParam); } catch (NoSuchFieldException e) { System.out.println(e); } catch (IllegalAccessException e) { System.out.println(e); } }