Top Banner
1 Reflection Reflection Copyright Kip Irvine, 2004. All rights reserved. Only students enrolled in COP 4338 at Florida International University may copy or print the contents of this slide show. Some materials used here are from Mark Allen Weiss, used by permission. by Kip Irvine Updated 09/01/04
36
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Java Reflection

1

ReflectionReflection

Copyright Kip Irvine, 2004. All rights reserved. Only students enrolled in COP 4338 at Florida International University may copy or print the contents of this slide show. Some materials used here are from Mark Allen Weiss, used by permission.

by Kip Irvine

Updated 09/01/04

Page 2: Java Reflection

Copyright 2002-2004, Kip Irvine 2

OverviewOverview Reflection API The Class class

– Class methods Array class Member interface Method class

– invoking a method, throwing exceptions Field class

– accessible objects

Page 3: Java Reflection

Copyright 2002-2004, Kip Irvine 3

Defining ReflectionDefining Reflection

Introduced in Java 1.1. Called the "Java Core Reflection API"

Allows you to find out information about any object, including its methods and fields, at run time.

Called an enabling technology because it supports Java language elements such as:– Java Beans, Serialization, and Remote Method Invocation

(RMI).

Page 4: Java Reflection

Copyright 2002-2004, Kip Irvine 4

Reflection Can be Used To . . .Reflection Can be Used To . . .

construct new class instances and new arrays access and modify fields of objects and classes invoke methods on objects and classes access and modify elements of arrays

Page 5: Java Reflection

Copyright 2002-2004, Kip Irvine 5

Reflection APIReflection API

Field class– get name and access for an arbitrary field

Method class– get info about an arbitrary method (and invoke it)

Constructor class– get info about an arbitrary constructor (and invoke it)

Class class– creates new instances of Field, Method, and Constructor

Array class– static methods to create and get info about arbitrary arrays

Page 6: Java Reflection

Copyright 2002-2004, Kip Irvine 6

The Class classThe Class class

Class objects represent a loaded class Such an object holds information about a class:

– its methods– its fields– its superclass– the interfaces it implements– whether it's an array

Page 7: Java Reflection

Copyright 2002-2004, Kip Irvine 7

Obtaining a Class ObjectObtaining a Class Object

At compile time, using the symbolic class name:Class c1 = String.class;

Class c2 = Employee[].class;

At runtime, by calling getClass( ) on any object:Class c3 = obj.getClass( );

At runtime, by passing a class name (string) to the forName( ) static method:

Class c = Class.forName( "java.util.Date" );

Page 8: Java Reflection

Copyright 2002-2004, Kip Irvine 8

Class MethodsClass Methods(1 of 4)(1 of 4)

public String getName( );

Returns the name of the class referred to by the Class object.

public boolean isInterface( );

Returns true if the Class object refers to an interface.

public boolean isArray( );

Returns true if the Class object refers to an array type.

public Class getSuperclass( );

Returns the superclass of the current Class object.

Page 9: Java Reflection

Copyright 2002-2004, Kip Irvine 9

Class MethodsClass Methods (2 of 4) (2 of 4)

public Class[] getInterfaces( );Returns array of interface classes implemented by this class.

public Class[] getClasses( );Returns array of inner classes within this class.

public Object newInstance( );Creates and returns an instance of this class.

public static Class forName( String name );Returns a Class object corresponding to a class name (static method)

Page 10: Java Reflection

Copyright 2002-2004, Kip Irvine 10

Class MethodsClass Methods (3 of 4) (3 of 4)

public Constructor[] getConstructors( );Returns an array of all public constructors in the current class.

(import java.lang.reflect.Constructor) public Method[] getDeclaredMethods( );Returns an array of all public and private methods declared in the current class or interface.

(import java.lang.reflect.Method)

public Method[] getMethods( );

Returns an array of all public methods in the current class, as well as those in all superclasses and superinterfaces.

See: MethodTest1.java

Page 11: Java Reflection

Copyright 2002-2004, Kip Irvine 11

Class MethodsClass Methods (4 of 4) (4 of 4)

public Method getMethod( String methodName, Class[] paramTypes );

Returns a Method object that reflects the method identified by name and parameter types in the current class and all superclasses. Method must be public.

public Method getDeclaredMethod( String methodName, Class[] paramTypes );

Returns a Method object that reflects the method identified by name and parameter types in the current class. Method may be private.

next: Array class

Page 12: Java Reflection

Copyright 2002-2004, Kip Irvine 12

The Array ClassThe Array Class

public class Array {

// all static methods:

public int getLength( Object arr );

public Object newInstance( Class elements, int length );

public Object get( Object arr, int index );

public void set( Object arr, int index, Object val );

// Various specialized versions, such as...

public int getInt( Object arr, int index );

public void setInt( Object arr, int index, int val );

}

import java.lang.reflect.Array;

Page 13: Java Reflection

Copyright 2002-2004, Kip Irvine 13

Array SamplesArray Samples

Canine[] kennel = new Canine[10];.int n = Array.getLength( kennel );

// set the contents of an array elementArray.set( kennel, (n-1), new Canine( "Spaniel" ) );

// get an object from the array, determine its class,// and display its value:

Object obj = Array.get( kennel, (n-1) );Class c1 = obj.getClass( );System.out.println( c1.getName( )

+ "-->" + obj.toString( ) );

Page 14: Java Reflection

Copyright 2002-2004, Kip Irvine 14

Two Ways to Declare an ArrayTwo Ways to Declare an Array

// first:

Canine kennel = new Canine[10];

// second:

Class c1 = Class.forName( "Canine" );

Canine kennel = (Canine[]) Array.newInstance( c1, 10 );

next: expanding an Array

Page 15: Java Reflection

Copyright 2002-2004, Kip Irvine 15

Example: Expanding an ArrayExample: Expanding an Array

Problem statement: write a function that receives an arbitrary array, allocates storage for twice the size of the array, copies the data to the new array, and returns the new array

Page 16: Java Reflection

Copyright 2002-2004, Kip Irvine 16

Example: Expanding an ArrayExample: Expanding an Array

Why won't this code work?

public static Object[] doubleArrayBad( Object[] arr ){

int newSize = arr.length * 2 + 1;

Object[] newArray = new Object[ newSize ];

for( int i = 0; i < arr.length; i++ )newArray[ i ] = arr[ i ];

return newArray;}

Page 17: Java Reflection

Copyright 2002-2004, Kip Irvine 17

Example: Expanding an ArrayExample: Expanding an Array

Ans: This method always returns an array of Object, rather than the type of the array being copied.

public static Object[] doubleArrayBad( Object[] arr ){

int newSize = arr.length * 2 + 1;

Object[] newArray = new Object[ newSize ];

for( int i = 0; i < arr.length; i++ )newArray[ i ] = arr[ i ];

return newArray;}

Page 18: Java Reflection

Copyright 2002-2004, Kip Irvine 18

Example: Expanding an ArrayExample: Expanding an Array

Use reflection to get the array type:

public Object[] doubleArray( Object[] arr ){

Class c1 = arr.getClass( );if( !c1.isArray( ) ) return null;

int oldSize = Array.getLength( arr );int newSize = oldSize * 2 + 1;

Object[] newArray = (Object[]) Array.newInstance(c1.getComponentType( ), newSize );

for( int i = 0; i < arr.length; i++ )newArray[ i ] = arr[ i ];

return newArray;}

see ArrayDouble.java

next: Member interface

Page 19: Java Reflection

Copyright 2002-2004, Kip Irvine 19

Member InterfaceMember Interface

Implemented by Constructor, Method, and Field Class getDeclaringClass( )

– returns the Class object representing the class or interface that declares the member or constructor represented by this Member.

int getModifiers( ) – returns the Java language modifiers for the member or

constructor represented by this Member, as an integer. String getName( )

– returns the simple name of the underlying member or constructor represented by this Member.

next: Method class

Page 20: Java Reflection

Copyright 2002-2004, Kip Irvine 20

Using a Method ObjectUsing a Method Object

Using a Method object, you can...– get its name and parameter list and– invoke the method

Obtain a Method from a signature, or get a list of all methods.

To specify the signature, create an array of Class objects representing the method’s parameter types.– Array will be zero-length if no parameters– Special Class objects for primitives

Page 21: Java Reflection

Copyright 2002-2004, Kip Irvine 21

Representing the Primitive TypesRepresenting the Primitive Types

Special Class objects representing the eight primitive types:– Byte.TYPE, Character.TYPE, Integer.TYPE, Long.TYPE,

Short.TYPE, Double.TYPE, Float.TYPE, Boolean.TYPE Void Class type:

– Void.TYPE Also Class types for arrays, such as ...

– class type for int[ ] is Integer.TYPE[].class– class type for int[ ][ ] is Integer.TYPE[][].class

Page 22: Java Reflection

Copyright 2002-2004, Kip Irvine 22

Method ClassMethod Class

public class Method implements Member

{

public Class getReturnType( );

public Class[] getParameterTypes( );

public String getName( );

public int getModifiers( );

public Class[] getExceptionTypes( );

public Object invoke( Object obj, Object[] args);

}

The modifiers are stored as a bit pattern; class Modifier has methods to interpret the bits.

Page 23: Java Reflection

Copyright 2002-2004, Kip Irvine 23

Method ExamplesMethod Examples

Retrieve the name of a method:(Method meth;)

String name = meth.getName( );

Retrieve an array of parameter types:Class parms[] = meth.getParameterTypes( );

Retrieve a method's return type:Class retType = meth.getReturnType( );

next: Invoking methods

Page 24: Java Reflection

Copyright 2002-2004, Kip Irvine 24

Method.invoke( )Method.invoke( )

public Object invoke(Object obj, Object[] args)

If the parameters or return types are primitives, they are wrapped using one of the eight wrapper classes.

– example: Integer.TYPE The first parameter to invoke is the controlling object

– (use null for static methods) The second parameter is the parameter list

– array of objects Disadvantages to using invoke( ):

– executes more slowly than static invocation– you have to handle all checked exceptions– you lose lots of compile-time checks

Page 25: Java Reflection

Copyright 2002-2004, Kip Irvine 25

Exceptions and Invoke( )Exceptions and Invoke( )

If invoked method throws an exception, invoke( ) will throw an InvocationTargetException– get the actual exception by calling getException

Lots of other exceptions to worry about before you call invoke:– Did class load? ClassNotFoundException– Was method found? NoSuchMethodException– Can you access method? IllegalAccessException

Page 26: Java Reflection

Copyright 2002-2004, Kip Irvine 26

Steps to Invoke a MethodSteps to Invoke a Method

Get a Class object, c. Get a Method object m, from c:

– Form an array of parameter types that match the method you want to invoke

– Call getDeclaredMethod( ), passing it the name of the method and the array of parameter types. Returns m.

Form an array of Object that contains the arguments to pass (second argument to m.invoke). – new String[ ] { "Breathing", "Fire" }

Pass the controlling object (or null if calling a static method) as the first parameter.

Call m.invoke( ), and catchInvocationTargetException

Page 27: Java Reflection

Copyright 2002-2004, Kip Irvine 27

Example: Invoking main( )Example: Invoking main( )

Class cl = Class.forName( className );

Class[] paramTypes = new Class[] { String[].class };

Method m = cl.getDeclaredMethod( "main", paramTypes );

Object[] args = new Object[] { new String[] { "Breathing", "Fire" } }

m.invoke( null, args );

See invokeMain.java

Calling: main( String[] args )

Simplified, with no error checking:

next: getting field values

Page 28: Java Reflection

Copyright 2002-2004, Kip Irvine 28

Invoking a ConstructorInvoking a Constructor

Class c1 = Class.forName("Villain");

Class[] paramTypes = new Class[] {String.class, Integer.TYPE };

Constructor m = c1.getConstructor( paramTypes );

Object[] arguments = new Object[] { "Darth Vader", new Integer(20) };

Villan v = (Villan) m.newInstance(arguments);

See NewInstanceExample.java

Call getConstructor( ), then call newInstance( )catch InstantiationException

Page 29: Java Reflection

Copyright 2002-2004, Kip Irvine 29

Getting Field Objects from a ClassGetting Field Objects from a Class

public Field getField( String name ) throws NoSuchFieldException, SecurityException

Returns a public Field object.

public Field[] getFields() throws SecurityException

Returns an array containing public fields of current class, interface, superclasses, and superinterfaces.

public Field[] getDeclaredFields() throws SecurityException

Returns an array containing all fields of current class and interfaces.

Page 30: Java Reflection

Copyright 2002-2004, Kip Irvine 30

Field ClassField Class

Extends the AccessibleObject class– provides changing the default access of class members

Things you can do with a Field object:– Get the field's name - String getName( )– Get the field's type – getType( )– Get or set a field's value – get( ), set( )– Check for equality – equals( )– Get its declaring class – Class getDeclaringClass( )– Get its modifiers - getModifiers( )

Page 31: Java Reflection

Copyright 2002-2004, Kip Irvine 31

Important Field MethodsImportant Field Methods

Implements Member interface: getName( ), getModifiers( ), and getDeclaringClass( )

Class getType( )– returns a Class object that identifies the declared type for the

field represented by this Field object. Object get( Object obj )

– Returns the value of the field represented by this Field, on the specified object.

void set( Object obj, Object value ) – sets the field represented by this Field object on the

specified object argument to the specified new value. (When referencing a static field, the obj argument is null)

Page 32: Java Reflection

Copyright 2002-2004, Kip Irvine 32

Important Field MethodsImportant Field Methods

boolean equals( Object obj ) – Compares this Field to another Field object. Return true iff

declared by same class, and have same name and type. Specific "get" methods:

– boolean getBoolean( Object obj ) gets the value of a static or instance boolean field.

– Also: getByte, getChar, getDouble, getFloat, getInt, getLong, and getShort

Specific "set" methods:– void setBoolean( Object obj, boolean z ) sets the value of a

field as a boolean on the specified object.– Also: setByte, setChar, setDouble, setFloat, setInt, setLong,

and setShort

Page 33: Java Reflection

Copyright 2002-2004, Kip Irvine 33

Get and Set for FieldGet and Set for Field

For instance:Object d = new Hero( );Field f = d.getClass( ).getField( "strength" );System.out.println( f.get( d ) );

Possible exceptions:– NoSuchFieldException, IllegalAccessException

(See MethodTest1.java, and SampleGet.java)

next: Accessible objects

Page 34: Java Reflection

Copyright 2002-2004, Kip Irvine 34

Accessible ObjectsAccessible Objects

Can request that Field, Method, and Constructor objects be “accessible.”– Request granted if no security manager, or if the existing

security manager allows it. Can invoke method or access field, even if

inaccessible via privacy rules.– Allows Java Object Serialization or other persistence

mechanisms to manipulate objects in a manner that would normally be prohibited.

Should only be used with discretion!

Page 35: Java Reflection

Copyright 2002-2004, Kip Irvine 35

AccessibleObject ClassAccessibleObject Class

Superclass of Field, Method, and Constructor boolean isAccessible( )

– Gets the value of the accessible flag for this object static void setAccessible( AccessibleObject[] array,

boolean flag ) – Sets the accessible flag for an array of objects with a single

security check void setAccessible( boolean flag )

– Sets the accessible flag for this object to the indicated boolean value

See: HeroSpy.java

Page 36: Java Reflection

Copyright 2002-2004, Kip Irvine 36

The EndThe End