Thanks to visit codestin.com
Credit goes to www.slideshare.net

Advanced Java ProgrammingLecture-02: ReflectionAatif Kamal,   Dept. of ComputingAatif.kamal@seecs.edu.pkStudy Source: http://download.oracle.com/javase/tutorial/reflect/
Reflection OverviewReflection APIThe “Class" classClass methodsArray classMember interfaceMethod classinvoking a method, throwing exceptionsField classaccessible objects
BackgroundPrograms are just another kind of dataSource code is textManipulate it line by line, or by parsing expressionsCompiled programs are data, tooIntegers and strings are bytes in memory that you interpret a certain wayInstructions in methods are just bytes tooNo reason why a program can't inspect itself
How objects workEvery object is either a reference or primitive type.objectclass Point {  public Point(int x, int y) {  }  public getX() {}  public getY() {}  protected int x, y;}5x3yclass{…}Point(int,int){…}getX(){…}getY()
5Defining ReflectionIntroduced in Java 1.1. Called the "Java Core Reflection API"Reflection is commonly used by programs which require the ability to examine or modify the runtime behavior of applications running in the Java virtual machineAllows you to find out information about any object, including its methods and fields, at run time.Can no longer get away with this called an enabling technology because it supports Java language elements such as:Java Beans, Serialization, and Remote Method Invocation (RMI).JBoss, Tomcat, Eclipse, etc. are reflection-based
6Reflection 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
Uses of ReflectionExtensibility Features An application may make use of external, user-defined classes by creating instances of extensibility objects using their fully-qualified names. Class Browsers and Visual Development Environments A class browser needs to be able to enumerate the members of classes. Visual development environments can benefit from making use of type information available in reflection to aid the developer in writing correct code. Debuggers and Test Tools Debuggers need to be able to examine private members on classes. Test harnesses can make use of reflection to systematically call a discoverable set APIs defined on a class, to insure a high level of code coverage in a test suite.
Drawbacks of ReflectionReflection is powerful, but should not be used indiscriminately. If it is possible to perform an operation without using reflection, then it is preferable to avoid using it.Performance OverheadBecause reflection involves types that are dynamically resolved, certain Java virtual machine optimizations can not be performed. Slower performance than their non-reflective counterparts,should be avoided in sections of code which are called frequently in performance-sensitive applications. Security RestrictionsReflection requires a runtime permission which may not be present when running under a security manager.  Code which has to run in a restricted security context, such as in an Applet.
Drawbacks of ReflectionExposure of InternalsSince reflection allows code to perform operations that would be illegal in non-reflective code, Accessing private fields and methods, the use of reflection can result in unexpected side-effects,Reflective code breaks abstractions and therefore may change behavior with upgrades of the platform.
Class  c = Class.forName(“java.lang.String”);Object o = c.newInstance();Reflection - ClassesReflection is a dynamic language featureUsed to query object and class informationstatic Class Class.forName(String className)Obtain a java.lang.Class objecti.e. Class.forName(“java.lang.String”) gets an object corresponding to class StringObject Class.newInstance()Object constructor in disguiseCreate  a new object of a given classThis makes a new empty string.
Running ExampleMost typical use of reflection:Take a class name, make a Class objectCreate object of that class, cast and use itStatically convertClass.newInstancenew T()1. String className = ...;2. Class  c = Class.forName(className);3. Object o = c.newInstance();4. T t      = (T) o;		new T1();new T2();...
12Reflection APIPackage java.lang.reflectField classget name and access for an arbitrary fieldMethod classget info about an arbitrary method (and invoke it)Constructor classget info about an arbitrary constructor (and invoke it)Classclasscreates new instances of Field, Method, and ConstructorArray classstatic methods to create and get info about arbitrary arrays…..With the exception of java.lang.reflect.ReflectPermission, none of the classes in java.lang.reflect have public constructors.
java.lang.ClassFor every type of object, the Java virtual machine instantiates an immutable instance of java.lang.ClassClass objects represent a loaded classProvides methods to examine the runtime properties of the object its methodsits fieldsits superclassthe interfaces it implementswhether it's an arrayProvides the ability to create new classes and objects. Entry point for all of the Reflection APIs
14Obtaining a Class ObjectTo get to these classes, it is necessary to invoke appropriate methods on Class.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" );
Retrieving Class Objects - ExamplesObject.getClass()the simplest way to get its Class is to invoke Object.getClass()Class c = "foo".getClass();    Returns the Class for StringClass c = System.console().getClass();  the Class corresponding to java.io.Console. enum E { A, B }; 	Class c = A.getClass(); A is is an instance of the enum E; thus getClass() returns   		the Class corresponding to the enumeration type E.byte[] bytes = new byte[1024]; 	Class c = bytes.getClass(); Since arrays are Objects, it is also possible to invoke 		getClass() on an instance of an array. The returned Class 		corresponds to an array with component type byte.
Retrieving Class Objects - ExamplesThe .class SyntaxIf the type is available but there is no instance then it is possible to obtain a Class by appending ".class" to the name of the type.This is also the easiest way to obtain the Class for a primitive type. boolean b; Class c = b.getClass();  	    // compile-time error Class c = boolean.class;               // correct Class c = java.io.PrintStream.class; Class c = int[ ][ ][ ].class;
Retrieving Class Objects - ExamplesClass.forName()If the fully-qualified name of a class is available, it is possible to get the corresponding Class using the static method Class.forName()Class driverObject = Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver"); Class c = Class.forName("com.duke.MyLocaleServiceProvider")TYPE Field for Primitive Type WrappersTwo ways .class syntax, more convenient and the preferred way Class c = boolean.class;Class c1 = String.class;Class c2 = Employee[].class;All primitive types & void has a wrapper class in java.lang, used for boxing of primitive types to reference types. Each wrapper class contains a field named TYPE which is equal to the Class for the primitive type being wrapped.Class c = Double.TYPE;
18Class Methods(1 of 4)public String getName( );Returns the name of the class referred to by the Class object.public booleanisInterface( );Returns true if the Class object refers to an interface.public booleanisArray( );Returns true if the Class object refers to an array type.public Class getSuperclass( );Returns the superclass of the current Class object.
19Class 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)
20Class 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.
Code Examples ReflectMethod.java & ReflectMethod2.java Class, Parent Class, Package nameShow all methods name, signatures – use getMethods()Bypassing Abstraction SpecificMethodInfoDemo.javaShowing method directly using getMethod()Bridge method ConceptSampleInvoke .java,RunMethod.java & InovkeMain.javaHow to execute a method – using Method.invoke()Recursion through ReflectionPrivateMethod.javaExecuting private methods of a class
22Member InterfaceImplemented by Constructor, Method, and FieldClass getDeclaringClass( ) returns the Class object representing the class or interface that declares the member or constructor represented by this Member. intgetModifiers( ) 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.
23Using a Method ObjectUsing a Method object, you can...get its name and parameter list andinvoke the methodObtain 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 parametersSpecial Class objects for primitives
24Representing the Primitive TypesSpecial Class objects representing the eight primitive types:Byte.TYPE, Character.TYPE, Integer.TYPE, Long.TYPE, Short.TYPE, Double.TYPE, Float.TYPE, Boolean.TYPEVoid Class type: Void.TYPEAlso Class types for arrays, such as ...class type for int[ ] is Integer.TYPE[].classclass type for int[ ][ ] is Integer.TYPE[][].class
25Method Classpublic class Method implements Member{public Class getReturnType( );public Class[] getParameterTypes( );public String getName( );public intgetModifiers( );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.
26Method ExamplesRetrieve the name of a method:Method meth = c1.getDeclaredMethods( );String name = meth.getName( );Retrieve an array of parameter types:Class parms[] = meth.getParameterTypes( );Retrieve a method's return type:Class retType = meth.getReturnType( );
27Method.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.TYPEThe first parameter to invoke is the controlling object (use null for static methods)The second parameter is the parameter listarray of objectsDisadvantages to using invoke( ):executes more slowly than static invocationyou have to handle all checked exceptionsyou lose lots of compile-time checks
28Exceptions and Invoke( )If invoked method throws an exception, invoke( ) will throw an InvocationTargetExceptionget the actual exception by calling getExceptionLots of other exceptions to worry about before you call invoke:Did class load? ClassNotFoundExceptionWas method found? NoSuchMethodExceptionCan you access method? IllegalAccessException
29Example: Invoking main( )Calling: main( String[] args )Simplified, with no error checking: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 );
30Invoking a ConstructorCall getConstructor( ), 	then call newInstance( )catch InstantiationExceptionClass 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);
31Member InterfaceImplemented by Constructor, Method, and FieldClass getDeclaringClass( ) returns the Class object representing the class or interface that declares the member or constructor represented by this Member. intgetModifiers( ) 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.
Code Examples ReflectMethod.java & ReflectMethod2.java Class, Parent Class, Package nameShow all methods name, signatures – use getMethods()Bypassing Abstraction SpecificMethodInfoDemo.javaShowing method directly using getMethod()Bridge method ConceptSampleInvoke .java,RunMethod.java & InovkeMain.javaHow to execute a method – using Method.invoke()Recursion through ReflectionPrivateMethod.javaExecuting private methods of a class
33The Array Classimport java.lang.reflect.Array;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 );}
34Array SamplesCanine[] 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( ) );
35Two 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
36Example: Expanding an ArrayProblem 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
37Example: Expanding an ArrayWhy won't this code work?public static Object[] doubleArrayBad( Object[] arr ){intnewSize = arr.length * 2 + 1;	Object[] newArray = new Object[ newSize ];	for( inti = 0; i < arr.length; i++ )newArray[ i ] = arr[ i ];	return newArray;}
38Example: Expanding an ArrayAns: This method always returns an array of Object, rather than the type of the array being copied.public static Object[] doubleArrayBad( Object[] arr ){intnewSize = arr.length * 2 + 1;	Object[] newArray = new Object[ newSize ];	for( inti = 0; i < arr.length; i++ )newArray[ i ] = arr[ i ];	return newArray;}
39Example: Expanding an ArrayUse reflection to get the array type:public Object[] doubleArray( Object[] arr ){	Class c1 = arr.getClass( );			if( !c1.isArray( ) ) return null;intoldSize = Array.getLength( arr );intnewSize = oldSize * 2 + 1;	Object[] newArray = (Object[]) Array.newInstance(		c1.getComponentType( ), newSize );	for( inti = 0; i < arr.length; i++ )newArray[ i ] = arr[ i ];	return newArray;}see ReflectionArrayTestjava
Assignment 02Extension One to Assignment 01Send a class object from one machine to another machine On recipient side through reflection show complete description of object Class, Parent class, Package, interface implemented Class Properties,  their access modifier,  datatype, name & valueClass methods, list all methods, access modifiers,  static/non static,  return Type, Name of method, Input parameters, exceptions And execute any static method object on the recipient side.  Save this assignment code as different version.
Next Lecture Java Logging - Log4J

Java Reflection Concept and Working

  • 1.
    Advanced Java ProgrammingLecture-02:ReflectionAatif Kamal, Dept. of [email protected] Source: http://download.oracle.com/javase/tutorial/reflect/
  • 2.
    Reflection OverviewReflection APIThe“Class" classClass methodsArray classMember interfaceMethod classinvoking a method, throwing exceptionsField classaccessible objects
  • 3.
    BackgroundPrograms are justanother kind of dataSource code is textManipulate it line by line, or by parsing expressionsCompiled programs are data, tooIntegers and strings are bytes in memory that you interpret a certain wayInstructions in methods are just bytes tooNo reason why a program can't inspect itself
  • 4.
    How objects workEveryobject is either a reference or primitive type.objectclass Point { public Point(int x, int y) { } public getX() {} public getY() {} protected int x, y;}5x3yclass{…}Point(int,int){…}getX(){…}getY()
  • 5.
    5Defining ReflectionIntroduced inJava 1.1. Called the "Java Core Reflection API"Reflection is commonly used by programs which require the ability to examine or modify the runtime behavior of applications running in the Java virtual machineAllows you to find out information about any object, including its methods and fields, at run time.Can no longer get away with this called an enabling technology because it supports Java language elements such as:Java Beans, Serialization, and Remote Method Invocation (RMI).JBoss, Tomcat, Eclipse, etc. are reflection-based
  • 6.
    6Reflection Can beUsed 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
  • 7.
    Uses of ReflectionExtensibilityFeatures An application may make use of external, user-defined classes by creating instances of extensibility objects using their fully-qualified names. Class Browsers and Visual Development Environments A class browser needs to be able to enumerate the members of classes. Visual development environments can benefit from making use of type information available in reflection to aid the developer in writing correct code. Debuggers and Test Tools Debuggers need to be able to examine private members on classes. Test harnesses can make use of reflection to systematically call a discoverable set APIs defined on a class, to insure a high level of code coverage in a test suite.
  • 8.
    Drawbacks of ReflectionReflectionis powerful, but should not be used indiscriminately. If it is possible to perform an operation without using reflection, then it is preferable to avoid using it.Performance OverheadBecause reflection involves types that are dynamically resolved, certain Java virtual machine optimizations can not be performed. Slower performance than their non-reflective counterparts,should be avoided in sections of code which are called frequently in performance-sensitive applications. Security RestrictionsReflection requires a runtime permission which may not be present when running under a security manager. Code which has to run in a restricted security context, such as in an Applet.
  • 9.
    Drawbacks of ReflectionExposureof InternalsSince reflection allows code to perform operations that would be illegal in non-reflective code, Accessing private fields and methods, the use of reflection can result in unexpected side-effects,Reflective code breaks abstractions and therefore may change behavior with upgrades of the platform.
  • 10.
    Class c= Class.forName(“java.lang.String”);Object o = c.newInstance();Reflection - ClassesReflection is a dynamic language featureUsed to query object and class informationstatic Class Class.forName(String className)Obtain a java.lang.Class objecti.e. Class.forName(“java.lang.String”) gets an object corresponding to class StringObject Class.newInstance()Object constructor in disguiseCreate a new object of a given classThis makes a new empty string.
  • 11.
    Running ExampleMost typicaluse of reflection:Take a class name, make a Class objectCreate object of that class, cast and use itStatically convertClass.newInstancenew T()1. String className = ...;2. Class c = Class.forName(className);3. Object o = c.newInstance();4. T t = (T) o; new T1();new T2();...
  • 12.
    12Reflection APIPackage java.lang.reflectFieldclassget name and access for an arbitrary fieldMethod classget info about an arbitrary method (and invoke it)Constructor classget info about an arbitrary constructor (and invoke it)Classclasscreates new instances of Field, Method, and ConstructorArray classstatic methods to create and get info about arbitrary arrays…..With the exception of java.lang.reflect.ReflectPermission, none of the classes in java.lang.reflect have public constructors.
  • 13.
    java.lang.ClassFor every typeof object, the Java virtual machine instantiates an immutable instance of java.lang.ClassClass objects represent a loaded classProvides methods to examine the runtime properties of the object its methodsits fieldsits superclassthe interfaces it implementswhether it's an arrayProvides the ability to create new classes and objects. Entry point for all of the Reflection APIs
  • 14.
    14Obtaining a ClassObjectTo get to these classes, it is necessary to invoke appropriate methods on Class.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" );
  • 15.
    Retrieving Class Objects- ExamplesObject.getClass()the simplest way to get its Class is to invoke Object.getClass()Class c = "foo".getClass();  Returns the Class for StringClass c = System.console().getClass();  the Class corresponding to java.io.Console. enum E { A, B }; Class c = A.getClass(); A is is an instance of the enum E; thus getClass() returns the Class corresponding to the enumeration type E.byte[] bytes = new byte[1024]; Class c = bytes.getClass(); Since arrays are Objects, it is also possible to invoke getClass() on an instance of an array. The returned Class corresponds to an array with component type byte.
  • 16.
    Retrieving Class Objects- ExamplesThe .class SyntaxIf the type is available but there is no instance then it is possible to obtain a Class by appending ".class" to the name of the type.This is also the easiest way to obtain the Class for a primitive type. boolean b; Class c = b.getClass(); // compile-time error Class c = boolean.class; // correct Class c = java.io.PrintStream.class; Class c = int[ ][ ][ ].class;
  • 17.
    Retrieving Class Objects- ExamplesClass.forName()If the fully-qualified name of a class is available, it is possible to get the corresponding Class using the static method Class.forName()Class driverObject = Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver"); Class c = Class.forName("com.duke.MyLocaleServiceProvider")TYPE Field for Primitive Type WrappersTwo ways .class syntax, more convenient and the preferred way Class c = boolean.class;Class c1 = String.class;Class c2 = Employee[].class;All primitive types & void has a wrapper class in java.lang, used for boxing of primitive types to reference types. Each wrapper class contains a field named TYPE which is equal to the Class for the primitive type being wrapped.Class c = Double.TYPE;
  • 18.
    18Class Methods(1 of4)public String getName( );Returns the name of the class referred to by the Class object.public booleanisInterface( );Returns true if the Class object refers to an interface.public booleanisArray( );Returns true if the Class object refers to an array type.public Class getSuperclass( );Returns the superclass of the current Class object.
  • 19.
    19Class Methods (2of 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)
  • 20.
    20Class Methods (3of 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.
  • 21.
    Code Examples ReflectMethod.java& ReflectMethod2.java Class, Parent Class, Package nameShow all methods name, signatures – use getMethods()Bypassing Abstraction SpecificMethodInfoDemo.javaShowing method directly using getMethod()Bridge method ConceptSampleInvoke .java,RunMethod.java & InovkeMain.javaHow to execute a method – using Method.invoke()Recursion through ReflectionPrivateMethod.javaExecuting private methods of a class
  • 22.
    22Member InterfaceImplemented byConstructor, Method, and FieldClass getDeclaringClass( ) returns the Class object representing the class or interface that declares the member or constructor represented by this Member. intgetModifiers( ) 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.
  • 23.
    23Using a MethodObjectUsing a Method object, you can...get its name and parameter list andinvoke the methodObtain 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 parametersSpecial Class objects for primitives
  • 24.
    24Representing the PrimitiveTypesSpecial Class objects representing the eight primitive types:Byte.TYPE, Character.TYPE, Integer.TYPE, Long.TYPE, Short.TYPE, Double.TYPE, Float.TYPE, Boolean.TYPEVoid Class type: Void.TYPEAlso Class types for arrays, such as ...class type for int[ ] is Integer.TYPE[].classclass type for int[ ][ ] is Integer.TYPE[][].class
  • 25.
    25Method Classpublic classMethod implements Member{public Class getReturnType( );public Class[] getParameterTypes( );public String getName( );public intgetModifiers( );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.
  • 26.
    26Method ExamplesRetrieve thename of a method:Method meth = c1.getDeclaredMethods( );String name = meth.getName( );Retrieve an array of parameter types:Class parms[] = meth.getParameterTypes( );Retrieve a method's return type:Class retType = meth.getReturnType( );
  • 27.
    27Method.invoke( )public Objectinvoke(Object obj, Object[] args)If the parameters or return types are primitives, they are wrapped using one of the eight wrapper classes.example: Integer.TYPEThe first parameter to invoke is the controlling object (use null for static methods)The second parameter is the parameter listarray of objectsDisadvantages to using invoke( ):executes more slowly than static invocationyou have to handle all checked exceptionsyou lose lots of compile-time checks
  • 28.
    28Exceptions and Invoke()If invoked method throws an exception, invoke( ) will throw an InvocationTargetExceptionget the actual exception by calling getExceptionLots of other exceptions to worry about before you call invoke:Did class load? ClassNotFoundExceptionWas method found? NoSuchMethodExceptionCan you access method? IllegalAccessException
  • 29.
    29Example: Invoking main()Calling: main( String[] args )Simplified, with no error checking: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 );
  • 30.
    30Invoking a ConstructorCallgetConstructor( ), then call newInstance( )catch InstantiationExceptionClass 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);
  • 31.
    31Member InterfaceImplemented byConstructor, Method, and FieldClass getDeclaringClass( ) returns the Class object representing the class or interface that declares the member or constructor represented by this Member. intgetModifiers( ) 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.
  • 32.
    Code Examples ReflectMethod.java& ReflectMethod2.java Class, Parent Class, Package nameShow all methods name, signatures – use getMethods()Bypassing Abstraction SpecificMethodInfoDemo.javaShowing method directly using getMethod()Bridge method ConceptSampleInvoke .java,RunMethod.java & InovkeMain.javaHow to execute a method – using Method.invoke()Recursion through ReflectionPrivateMethod.javaExecuting private methods of a class
  • 33.
    33The Array Classimportjava.lang.reflect.Array;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 );}
  • 34.
    34Array SamplesCanine[] 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( ) );
  • 35.
    35Two Ways toDeclare 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
  • 36.
    36Example: Expanding anArrayProblem 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
  • 37.
    37Example: Expanding anArrayWhy won't this code work?public static Object[] doubleArrayBad( Object[] arr ){intnewSize = arr.length * 2 + 1; Object[] newArray = new Object[ newSize ]; for( inti = 0; i < arr.length; i++ )newArray[ i ] = arr[ i ]; return newArray;}
  • 38.
    38Example: Expanding anArrayAns: This method always returns an array of Object, rather than the type of the array being copied.public static Object[] doubleArrayBad( Object[] arr ){intnewSize = arr.length * 2 + 1; Object[] newArray = new Object[ newSize ]; for( inti = 0; i < arr.length; i++ )newArray[ i ] = arr[ i ]; return newArray;}
  • 39.
    39Example: Expanding anArrayUse reflection to get the array type:public Object[] doubleArray( Object[] arr ){ Class c1 = arr.getClass( ); if( !c1.isArray( ) ) return null;intoldSize = Array.getLength( arr );intnewSize = oldSize * 2 + 1; Object[] newArray = (Object[]) Array.newInstance( c1.getComponentType( ), newSize ); for( inti = 0; i < arr.length; i++ )newArray[ i ] = arr[ i ]; return newArray;}see ReflectionArrayTestjava
  • 40.
    Assignment 02Extension Oneto Assignment 01Send a class object from one machine to another machine On recipient side through reflection show complete description of object Class, Parent class, Package, interface implemented Class Properties, their access modifier, datatype, name & valueClass methods, list all methods, access modifiers, static/non static, return Type, Name of method, Input parameters, exceptions And execute any static method object on the recipient side. Save this assignment code as different version.
  • 41.
    Next Lecture JavaLogging - Log4J