Java Reflection


Published on

Published in: Technology, Education
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Java Reflection

  1. 1. 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
  2. 2. Overview <ul><li>Reflection API </li></ul><ul><li>The Class class </li></ul><ul><ul><li>Class methods </li></ul></ul><ul><li>Array class </li></ul><ul><li>Member interface </li></ul><ul><li>Method class </li></ul><ul><ul><li>invoking a method, throwing exceptions </li></ul></ul><ul><li>Field class </li></ul><ul><ul><li>accessible objects </li></ul></ul>
  3. 3. Defining Reflection <ul><li>Introduced in Java 1.1. Called the &quot; Java Core Reflection API&quot; </li></ul><ul><li>Allows you to find out information about any object, including its methods and fields, at run time . </li></ul><ul><li>Called an enabling technology because it supports Java language elements such as: </li></ul><ul><ul><li>Java Beans, Serialization, and Remote Method Invocation (RMI). </li></ul></ul>
  4. 4. Reflection Can be Used To . . . <ul><li>construct new class instances and new arrays </li></ul><ul><li>access and modify fields of objects and classes </li></ul><ul><li>invoke methods on objects and classes </li></ul><ul><li>access and modify elements of arrays </li></ul>
  5. 5. Reflection API <ul><li>Field class </li></ul><ul><ul><li>get name and access for an arbitrary field </li></ul></ul><ul><li>Method class </li></ul><ul><ul><li>get info about an arbitrary method (and invoke it) </li></ul></ul><ul><li>Constructor class </li></ul><ul><ul><li>get info about an arbitrary constructor (and invoke it) </li></ul></ul><ul><li>Class class </li></ul><ul><ul><li>creates new instances of Field, Method, and Constructor </li></ul></ul><ul><li>Array class </li></ul><ul><ul><li>static methods to create and get info about arbitrary arrays </li></ul></ul>
  6. 6. The Class class <ul><li>Class objects represent a loaded class </li></ul><ul><li>Such an object holds information about a class: </li></ul><ul><ul><li>its methods </li></ul></ul><ul><ul><li>its fields </li></ul></ul><ul><ul><li>its superclass </li></ul></ul><ul><ul><li>the interfaces it implements </li></ul></ul><ul><ul><li>whether it's an array </li></ul></ul>
  7. 7. Obtaining a Class Object <ul><li>At compile time, using the symbolic class name: </li></ul><ul><ul><ul><li>Class c1 = String.class; </li></ul></ul></ul><ul><ul><ul><li>Class c2 = Employee[].class; </li></ul></ul></ul><ul><li>At runtime, by calling getClass( ) on any object: </li></ul><ul><ul><ul><li>Class c3 = obj.getClass( ); </li></ul></ul></ul><ul><li>At runtime, by passing a class name (string) to the forName( ) static method: </li></ul><ul><ul><li>Class c = Class.forName( &quot;java.util.Date&quot; ); </li></ul></ul>
  8. 8. Class Methods (1 of 4) <ul><li>public String getName( ); </li></ul><ul><li>Returns the name of the class referred to by the Class object. </li></ul><ul><li>public boolean isInterface( ); </li></ul><ul><li>Returns true if the Class object refers to an interface. </li></ul><ul><li>public boolean isArray( ); </li></ul><ul><li>Returns true if the Class object refers to an array type. </li></ul><ul><li>public Class getSuperclass( ); </li></ul><ul><li>Returns the superclass of the current Class object. </li></ul>
  9. 9. Class Methods (2 of 4) <ul><li>public Class[] getInterfaces( ); </li></ul><ul><li>Returns array of interface classes implemented by this class. </li></ul><ul><li>public Class[] getClasses( ); </li></ul><ul><li>Returns array of inner classes within this class. </li></ul><ul><li>public Object newInstance( ); </li></ul><ul><li>Creates and returns an instance of this class. </li></ul><ul><li>public static Class forName( String name ); </li></ul><ul><li>Returns a Class object corresponding to a class name (static method) </li></ul>
  10. 10. Class Methods (3 of 4) <ul><li>public Constructor[] getConstructors( ); </li></ul><ul><li>Returns an array of all public constructors in the current class. </li></ul><ul><li>(import java.lang.reflect.Constructor) </li></ul><ul><li>public Method[] getDeclaredMethods( ); </li></ul><ul><li>Returns an array of all public and private methods declared in the current class or interface. </li></ul><ul><li>(import java.lang.reflect.Method) </li></ul><ul><li>public Method[] getMethods( ); </li></ul><ul><li>Returns an array of all public methods in the current class, as well as those in all superclasses and superinterfaces. </li></ul>See:
  11. 11. Class Methods (4 of 4) <ul><li>public Method getMethod( String methodName, Class[] paramTypes ); </li></ul><ul><li>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. </li></ul><ul><li>public Method getDeclaredMethod( String methodName, Class[] paramTypes ); </li></ul><ul><li>Returns a Method object that reflects the method identified by name and parameter types in the current class. Method may be private. </li></ul>next: Array class
  12. 12. The Array Class <ul><li>public class Array { </li></ul><ul><ul><li>// all static methods: </li></ul></ul><ul><ul><li>public int getLength ( Object arr ); </li></ul></ul><ul><ul><li>public Object newInstance ( Class elements, int length ); </li></ul></ul><ul><ul><li>public Object get ( Object arr, int index ); </li></ul></ul><ul><ul><li>public void set ( Object arr, int index, Object val ); </li></ul></ul><ul><ul><li>// Various specialized versions, such as... </li></ul></ul><ul><ul><li>public int getInt ( Object arr, int index ); </li></ul></ul><ul><ul><li>public void setInt ( Object arr, int index, int val ); </li></ul></ul><ul><li>} </li></ul>import java.lang.reflect.Array;
  13. 13. Array Samples Canine[] kennel = new Canine[10]; . int n = Array.getLength ( kennel ); // set the contents of an array element Array.set ( kennel, (n-1), new Canine( &quot;Spaniel&quot; ) ); // 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 ( ) + &quot;-->&quot; + obj.toString( ) );
  14. 14. Two Ways to Declare an Array // first: Canine kennel = new Canine[10]; // second: Class c1 = Class.forName ( &quot;Canine&quot; ); Canine kennel = (Canine[]) Array.newInstance ( c1, 10 ); next: expanding an Array
  15. 15. Example: Expanding an Array <ul><li>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 </li></ul>
  16. 16. Example: Expanding an Array <ul><li>Why won't this code work? </li></ul>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; }
  17. 17. Example: Expanding an Array <ul><li>Ans: This method always returns an array of Object, rather than the type of the array being copied. </li></ul>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; }
  18. 18. Example: Expanding an Array <ul><li>Use reflection to get the array type: </li></ul>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 next: Member interface
  19. 19. Member Interface <ul><li>Implemented by Constructor, Method, and Field </li></ul><ul><li>Class getDeclaringClass( ) </li></ul><ul><ul><li>returns the Class object representing the class or interface that declares the member or constructor represented by this Member. </li></ul></ul><ul><li>int getModifiers( ) </li></ul><ul><ul><li>returns the Java language modifiers for the member or constructor represented by this Member, as an integer. </li></ul></ul><ul><li>String getName( ) </li></ul><ul><ul><li>returns the simple name of the underlying member or constructor represented by this Member. </li></ul></ul>next: Method class
  20. 20. Using a Method Object <ul><li>Using a Method object, you can... </li></ul><ul><ul><li>get its name and parameter list and </li></ul></ul><ul><ul><li>invoke the method </li></ul></ul><ul><li>Obtain a Method from a signature, or get a list of all methods. </li></ul><ul><li>To specify the signature, create an array of Class objects representing the method’s parameter types. </li></ul><ul><ul><li>Array will be zero-length if no parameters </li></ul></ul><ul><ul><li>Special Class objects for primitives </li></ul></ul>
  21. 21. Representing the Primitive Types <ul><li>Special Class objects representing the eight primitive types: </li></ul><ul><ul><li>Byte.TYPE, Character.TYPE, Integer.TYPE, Long.TYPE, Short.TYPE, Double.TYPE, Float.TYPE, Boolean.TYPE </li></ul></ul><ul><li>Void Class type: </li></ul><ul><ul><li>Void.TYPE </li></ul></ul><ul><li>Also Class types for arrays, such as ... </li></ul><ul><ul><li>class type for int[ ] is Integer.TYPE[].class </li></ul></ul><ul><ul><li>class type for int[ ][ ] is Integer.TYPE[][].class </li></ul></ul>
  22. 22. Method Class <ul><li>public class Method implements Member </li></ul><ul><li>{ </li></ul><ul><ul><li>public Class getReturnType( ); </li></ul></ul><ul><ul><li>public Class[] getParameterTypes( ); </li></ul></ul><ul><ul><li>public String getName( ); </li></ul></ul><ul><ul><li>public int getModifiers( ); </li></ul></ul><ul><ul><li>public Class[] getExceptionTypes( ); </li></ul></ul><ul><ul><li>public Object invoke( Object obj, Object[] args); </li></ul></ul><ul><li>} </li></ul><ul><li>The modifiers are stored as a bit pattern; class Modifier has methods to interpret the bits. </li></ul>
  23. 23. Method Examples <ul><li>Retrieve the name of a method: </li></ul><ul><ul><ul><li>(Method meth;) </li></ul></ul></ul><ul><ul><ul><li>String name = meth.getName( ); </li></ul></ul></ul><ul><li>Retrieve an array of parameter types: </li></ul><ul><ul><ul><li>Class parms[] = meth.getParameterTypes( ); </li></ul></ul></ul><ul><li>Retrieve a method's return type: </li></ul><ul><ul><ul><li>Class retType = meth.getReturnType( ); </li></ul></ul></ul>next: Invoking methods
  24. 24. Method.invoke( ) <ul><li>public Object invoke(Object obj, Object[] args) </li></ul><ul><li>If the parameters or return types are primitives, they are wrapped using one of the eight wrapper classes. </li></ul><ul><ul><li>example: Integer.TYPE </li></ul></ul><ul><li>The first parameter to invoke is the controlling object </li></ul><ul><ul><li>(use null for static methods) </li></ul></ul><ul><li>The second parameter is the parameter list </li></ul><ul><ul><li>array of objects </li></ul></ul><ul><li>Disadvantages to using invoke( ): </li></ul><ul><ul><li>executes more slowly than static invocation </li></ul></ul><ul><ul><li>you have to handle all checked exceptions </li></ul></ul><ul><ul><li>you lose lots of compile-time checks </li></ul></ul>
  25. 25. Exceptions and Invoke( ) <ul><li>If invoked method throws an exception, invoke( ) will throw an InvocationTargetException </li></ul><ul><ul><li>get the actual exception by calling getException </li></ul></ul><ul><li>Lots of other exceptions to worry about before you call invoke: </li></ul><ul><ul><li>Did class load? ClassNotFoundException </li></ul></ul><ul><ul><li>Was method found? NoSuchMethodException </li></ul></ul><ul><ul><li>Can you access method? IllegalAccessException </li></ul></ul>
  26. 26. Steps to Invoke a Method <ul><li>Get a Class object, c . </li></ul><ul><li>Get a Method object m , from c: </li></ul><ul><ul><li>Form an array of parameter types that match the method you want to invoke </li></ul></ul><ul><ul><li>Call getDeclaredMethod ( ), passing it the name of the method and the array of parameter types. Returns m . </li></ul></ul><ul><li>Form an array of Object that contains the arguments to pass (second argument to m .invoke). </li></ul><ul><ul><li>new String[ ] { &quot;Breathing&quot;, &quot;Fire&quot; } </li></ul></ul><ul><li>Pass the controlling object (or null if calling a static method) as the first parameter. </li></ul><ul><li>Call m .invoke( ), and catch InvocationTargetException </li></ul>
  27. 27. Example: Invoking main( ) Class cl = Class.forName( className ); Class[] paramTypes = new Class[] { String[].class }; Method m = cl.getDeclaredMethod( &quot;main&quot;, paramTypes ); Object[] args = new Object[] { new String[] { &quot;Breathing&quot;, &quot;Fire&quot; } } m.invoke( null, args ); See Calling: main( String[] args ) Simplified, with no error checking: next: getting field values
  28. 28. Invoking a Constructor Class c1 = Class.forName(&quot;Villain&quot;); Class[] paramTypes = new Class[] {String.class, Integer.TYPE }; Constructor m = c1.getConstructor( paramTypes ); Object[] arguments = new Object[] { &quot;Darth Vader&quot;, new Integer(20) }; Villan v = (Villan) m.newInstance(arguments); See Call getConstructor( ), then call newInstance( ) catch InstantiationException
  29. 29. Getting Field Objects from a Class <ul><li>public Field getField( String name ) </li></ul><ul><li>throws NoSuchFieldException, SecurityException </li></ul><ul><li>Returns a public Field object. </li></ul><ul><li>public Field[] getFields() throws SecurityException </li></ul><ul><li>Returns an array containing public fields of current class, interface, superclasses, and superinterfaces. </li></ul><ul><li>public Field[] getDeclaredFields() throws SecurityException </li></ul><ul><li>Returns an array containing all fields of current class and interfaces. </li></ul>
  30. 30. Field Class <ul><li>Extends the AccessibleObject class </li></ul><ul><ul><li>provides changing the default access of class members </li></ul></ul><ul><li>Things you can do with a Field object: </li></ul><ul><ul><li>Get the field's name - String getName( ) </li></ul></ul><ul><ul><li>Get the field's type – getType( ) </li></ul></ul><ul><ul><li>Get or set a field's value – get( ), set( ) </li></ul></ul><ul><ul><li>Check for equality – equals( ) </li></ul></ul><ul><ul><li>Get its declaring class – Class getDeclaringClass( ) </li></ul></ul><ul><ul><li>Get its modifiers - getModifiers( ) </li></ul></ul>
  31. 31. Important Field Methods <ul><li>Implements Member interface: getName( ), getModifiers( ), and getDeclaringClass( ) </li></ul><ul><li>Class getType( ) </li></ul><ul><ul><li>returns a Class object that identifies the declared type for the field represented by this Field object. </li></ul></ul><ul><li>Object get( Object obj ) </li></ul><ul><ul><li>Returns the value of the field represented by this Field, on the specified object. </li></ul></ul><ul><li>void set( Object obj, Object value ) </li></ul><ul><ul><li>sets the field represented by this Field object on the specified object argument to the specified new value. </li></ul></ul><ul><li>(When referencing a static field, the obj argument is null) </li></ul>
  32. 32. Important Field Methods <ul><li>boolean equals( Object obj ) </li></ul><ul><ul><li>Compares this Field to another Field object. Return true iff declared by same class, and have same name and type. </li></ul></ul><ul><li>Specific &quot;get&quot; methods: </li></ul><ul><ul><li>boolean getBoolean( Object obj ) gets the value of a static or instance boolean field. </li></ul></ul><ul><ul><li>Also: getByte, getChar, getDouble, getFloat, getInt, getLong, and getShort </li></ul></ul><ul><li>Specific &quot;set&quot; methods: </li></ul><ul><ul><li>void setBoolean( Object obj, boolean z ) sets the value of a field as a boolean on the specified object. </li></ul></ul><ul><ul><li>Also: setByte, setChar, setDouble, setFloat, setInt, setLong, and setShort </li></ul></ul>
  33. 33. Get and Set for Field <ul><li>For instance: </li></ul><ul><ul><li>Object d = new Hero( ); </li></ul></ul><ul><ul><li>Field f = d.getClass( ).getField( &quot;strength&quot; ); </li></ul></ul><ul><ul><li>System.out.println( f.get( d ) ); </li></ul></ul><ul><li>Possible exceptions: </li></ul><ul><ul><li>NoSuchFieldException, IllegalAccessException </li></ul></ul>(See, and next: Accessible objects
  34. 34. Accessible Objects <ul><li>Can request that Field, Method, and Constructor objects be “accessible.” </li></ul><ul><ul><li>Request granted if no security manager, or if the existing security manager allows it. </li></ul></ul><ul><li>Can invoke method or access field, even if inaccessible via privacy rules. </li></ul><ul><ul><li>Allows Java Object Serialization or other persistence mechanisms to manipulate objects in a manner that would normally be prohibited. </li></ul></ul><ul><li>Should only be used with discretion! </li></ul>
  35. 35. AccessibleObject Class <ul><li>Superclass of Field, Method, and Constructor </li></ul><ul><li>boolean isAccessible( ) </li></ul><ul><ul><li>Gets the value of the accessible flag for this object </li></ul></ul><ul><li>static void setAccessible( AccessibleObject[] array, boolean flag ) </li></ul><ul><ul><li>Sets the accessible flag for an array of objects with a single security check </li></ul></ul><ul><li>void setAccessible( boolean flag ) </li></ul><ul><ul><li>Sets the accessible flag for this object to the indicated boolean value </li></ul></ul>See:
  36. 36. The End