• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
Java Reflection
 

Java Reflection

on

  • 3,164 views

 

Statistics

Views

Total Views
3,164
Views on SlideShare
3,148
Embed Views
16

Actions

Likes
1
Downloads
137
Comments
0

2 Embeds 16

http://www.snailee.pe.kr 15
http://www.slideshare.net 1

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    Java Reflection Java Reflection Presentation Transcript

    • 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
    • Overview
      • Reflection API
      • The Class class
        • Class methods
      • Array class
      • Member interface
      • Method class
        • invoking a method, throwing exceptions
      • Field class
        • accessible objects
    • Defining 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).
    • 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
    • Reflection 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
    • The 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
    • Obtaining 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" );
    • Class Methods (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.
    • Class Methods (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)
    • Class Methods (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
    • Class Methods (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
    • The 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;
    • 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( "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( ) );
    • Two 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
    • Example: 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
    • Example: 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; }
    • Example: 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; }
    • Example: 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
    • Member 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
    • Using 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
    • Representing 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
    • Method 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.
    • Method 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
    • 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
    • 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
    • Steps 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[ ] { &quot;Breathing&quot;, &quot;Fire&quot; }
      • Pass the controlling object (or null if calling a static method) as the first parameter.
      • Call m .invoke( ), and catch InvocationTargetException
    • 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 invokeMain.java Calling: main( String[] args ) Simplified, with no error checking: next: getting field values
    • 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 NewInstanceExample.java Call getConstructor( ), then call newInstance( ) catch InstantiationException
    • Getting 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.
    • Field 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( )
    • Important 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)
    • Important 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 &quot;get&quot; 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 &quot;set&quot; 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
    • Get and Set for Field
      • For instance:
        • Object d = new Hero( );
        • Field f = d.getClass( ).getField( &quot;strength&quot; );
        • System.out.println( f.get( d ) );
      • Possible exceptions:
        • NoSuchFieldException, IllegalAccessException
      (See MethodTest1.java, and SampleGet.java) next: Accessible objects
    • Accessible 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!
    • AccessibleObject 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
    • The End