






Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!







1
2
l What is Reflection
l The Class class
l Run Time Type Identification (RTTI)
l Getting Class Information
l Accessing an arbitrary object’s fields
l Advanced features
3
l Introduced in Java 1.
l Allows you to find out information about any object, including its methods and fields, even if the type of the object is not known at compile time
l Added to the language to support Beans, Serialization, RMI, and other goodies.
l Reflection is an enabling technology.
4
The Class Object
l Class objects represent a loaded class
l Can find out information about the class
5
Obtaining a Class Object
l If you know a class name, can get it: Class c1 = String.class; Class c2 = Employee[].class; l Can get it from any object, using getClass : void printType( Object obj ) { Class c3 = obj.getClass( ); System.out.println( c.toString( ) ); }
l Can get it by loading the class using the forName static method: Class c = Class.forName( "java.util.Date" );
6
public class Class { public String getName( ); public boolean isInterface( ); public boolean isArray( ); public Class getSuperclass( ); public Class[] getInterfaces( ); public Class[] getClasses( ); // inner classes public Object newInstance( ); public static Class forName( String name ); public Method[] getDeclaredMethods( ); public Method[] getMethods( ); }
What’s In Class?
10
The Array Class
public class Array { // All of these are static public int getLength( Object arr ); public Object newInstance( Class comp, int length ); public Object get( Object arr, int index ); public void set( Object arr, int index, Object val );
// Various specialized versions: public int getInt( Object arr, int index ); public void setInt( Object arr, int index, int val ); }
11
Accessing a Class’ Members
l From Class object, you can get Method objects that reflect all methods, Field objects that reflect all fields, and Constructor objects that reflect all constructors.
l Two versions (use Field as example)
12
public void printClassMethods( String name ) { try { Class cl = Class.forName( name ); Constructor c = cl.getConstructors( ); for( int i = 0; i < c.length; i++ ) System.out.println( c.toString( ) ); Method m [] = cl.getMethods( ); for( int i = 0; i < m.length; i++ ) System.out.println( m.toString( ) ); } catch( ClassNotFoundException e ) { System.out.println( name + " not found" ); }
13
Using a Method Object
l From Method object
l To specify the signature, give an array of Class objects that represent the types of the parameters.
14
What’s In Method Class
l Various accessors to get info. Also invoke. public class Method { public Class getReturnType( ); public Class[] getParameterTypes( ); public String getName( ); public int getModifiers( ); public Class[] getExceptionTypes( ); public Object invoke( Object o, Object[] args); }
l The modifiers are stored as a bit pattern; class Modifier has methods to interpret the bits.
15
Some Details
l Parameters and return types are Objects. If the actual types are primitives, they will be wrapped using one of the eight wrapper classes.
l The first parameter to invoke is the controlling object (good idea to use null for static methods, but not required). The second parameter is the parameter list.
l When you use invoke beware:
19
Example: Run any main
// Assumes import statements present // Run the main for any class className // This is the main logic; exception handling is on next slide public static void invokeMain( String className, Object[] params ) { try { Class cl = Class.forName( className ); Class[] mainsParamTypes = new Class[] { String[].class }; Method mainMethod = cl.getMethod( "main", mainsParamTypes ); if( !Modifier.isStatic( mainMethod.getModifiers( ) ) ) System.out.println( "Oops... main is not static!" ); else if( mainMethod.getReturnType( ) != Void.TYPE ) System.out.println( "Oops... main doesn’t return void!" ); else mainMethod.invoke( null, params ); }
20
Example: Run any main (exceptions) catch( ClassNotFoundException e ) { System.out.println( "Cannot find " + className ); } catch( NoSuchMethodException e ) { System.out.println( "Cannot find main in " + className ); } catch( IllegalAccessException e ) { System.out.println( "Cannot invoke main in " + className ); } catch( InvocationTargetException e ) { System.out.println( "main threw an exception" ); e.getTargetException( ).printStackTrace( ); } }
21
The Field Class
l Can get list of all fields from a Class object.
l Once you have a Field class representation of an object, you can get or set its value.
l For instance (assume Date has month field, as a string): Object d = new Date( "July 1, 1993" ); Field f = d.getClass( ).getField( "month" ); System.out.println( f.get( d ) );
l Security check is performed: if field is inaccessible, an IllegalAccessException is thrown. And fields should be private!!
22
get and set For Field
l get and set return value in an Object.
l Primitives are wrapped.
l Special versions for convenience (e.g. getInt , getDouble , setInt , etc.)
23
Java 1.2: Accessible Objects
l Can request that Field , Method , and Constructor objects be “accessible.”
l Request granted if no security manager, or if the existing security manager allows it.
l Can invoke method or access field, even if inaccessible via privacy rules.
l Blatant security hole, means now you need to know what a security manager is. Stay tuned....
24
Example Of Accessing Private Data import java.lang.reflect.*; class Hidden { private static int SECRET = 3737; } class Spy { public static int getHiddenSecret( ) { try { Field f = Hidden.class.getDeclaredField( "SECRET" ); f.setAccessible( true ); // Make private field accessible return f.getInt( null ); } catch( NoSuchFieldException e ) { } catch( IllegalAccessException e ) { } catch( java.security.AccessControlException e ) { System.out.println( "Security manager objects to this!" ); } return -1; } }
28
Proxy Pattern
l With the proxy pattern, FooImpl and FooProxy are not usually constructed directly by the user. Instead, they are handed out by a FooFactory class and only Foo is visible: public class FooFactory { public static Foo allocateFoo( ) { return new FooProxy( new FooImpl( ) ); } private FooFactory( ) { } // No FooFactory objects }
l With this pattern, user is oblivious to the fact that they have a proxy!
l Easy to change implementation of the concrete Foo instances
29
Dynamic Proxies
l Proxies useful to
l If interfaces are large, the code to write new proxies is cumbersome and repeated.
l Reflection can do this for you automatically.
l Downside is that reflection might be too slow; depends on what the proxy is doing.
30
Code Is Straightforward
l Uses two classes:
31
Generation of Foo Proxy Class public class FooFactory { public static Foo allocateFoo( ) { return (Foo) Proxy.newProxyInstance( Foo.class.getClassLoader( ), new Class[] { Foo.class }, new FooHandler( new FooImpl( ) ) ); } private FooFactory( ) { } // No FooFactory objects }
class FooHandler implements InvocationHandler { public FooHandler( Object d ) { delegate = d; } public Object invoke( Object proxy, Method meth, Object[] args ) throws Throwable { System.out.println( "Hello" ); return meth.invoke( delegate, args ); } private Object delegate; }
32
Dynamic Proxy Details
l Can have several interfaces implemented; order of interfaces matters if interfaces declare common methods
l Generated Proxy classes
l newProxyInstance actually calls getProxyClass to get a Class object, and then newInstance on the Class object.
33
What The New Proxy Class Is public final class GeneratedProxy extends Proxy implements Foo { public GeneratedProxy( InvocationHandler h ) { super( h ); handler = super.h; } public int meth2( ) { Object ret = null; try { Method m = myClass.getMethod( "meth2", new Class[] { } ); ret = handler.invoke( this, m, new Object[] { } ); } catch( Throwable e ) { if( e instanceof RuntimeException ) throw (RuntimeException) e; if( e instanceof Error ) throw (Error) e; } return ((Integer)ret).intValue( ); } ... private InvocationHandler handler; private static final Class myClass = Foo.class; }