Presentation is loading. Please wait.

Presentation is loading. Please wait.

Slide 11.1 Advanced Programming 2004, based on LY Stefanus’s Slides Reflection Reflection is the ability for a class or object to examine itself. Java.

Similar presentations


Presentation on theme: "Slide 11.1 Advanced Programming 2004, based on LY Stefanus’s Slides Reflection Reflection is the ability for a class or object to examine itself. Java."— Presentation transcript:

1 slide 11.1 Advanced Programming 2004, based on LY Stefanus’s Slides Reflection Reflection is the ability for a class or object to examine itself. Java Reflection API is supported by the classes in the java.lang.reflect package. Within the limits imposed by Java security manager, one can find out what constructors, methods, and fields (variables) a class has. Classes in Java are represented at runtime by instances of the java.lang.Class class. There’s a Class object for every class. The Class object is the basis for reflection.

2 slide 11.2 Advanced Programming 2004, based on LY Stefanus’s Slides the Class class The Class reference associated with a particular object can be obtained with the getClass() method: String myString = ”hello”; Class myClass = myString.getClass(); We can also get the Class reference for a particular class using the.class notation: Class myClass = myString.class; One thing we can do with the Class object is ask for the name of the object’s class: System.out.println(myClass.getName()); //”java.lang.String”

3 slide 11.3 Advanced Programming 2004, based on LY Stefanus’s Slides A Class object can be asked to produce a new instance of its type of object. try { String s2 = (String) myClass.newInstance(); } catch ( InstantiationException e ) {... } catch ( IllegalAccessException e ) {... } newInstance() has a return type of Object. InstantiationException indicates that we’re trying to instantiate an abstract class or an interface. IllegalAccessException is a more general exception that indicates we can’t access a constructor for the object.

4 slide 11.4 Advanced Programming 2004, based on LY Stefanus’s Slides We can look up a class by name. forName() is a static method of Class class that returns a Class object given its name as a String: try { Class abcClass = Class.forName(”abc”); } catch ( ClassNotFoundException e ) {... } ClassNotFoundException is thrown if the class can’t be located.

5 slide 11.5 Advanced Programming 2004, based on LY Stefanus’s Slides The Class Objects of Primitive Types Represented by special static TYPE fields of their respective wrapper classes. For example, use Integer.TYPE for the Class object of int; use Double.TYPE for the Class object of double.

6 slide 11.6 Advanced Programming 2004, based on LY Stefanus’s Slides Methods in the Class class Field[] getFields( ) –Get all public variables, including inherited ones. Field getField( String name ) –Get the specified public variable, which may be inherited. Field[] getDeclaredFields( ) –Get all public and nonpublic variables declared in this class (not including those inherited) Field getDeclaredField( String name ) –Get the specified variable, public or nonpublic, declared in this class (inherited variables not considered)

7 slide 11.7 Advanced Programming 2004, based on LY Stefanus’s Slides Method[] getMethods( ) –Get all public methods, including inherited ones. Method getMethod( String name, Class[] argumentTypes) –Get the specified public method whose arguments match the types listed in argumentTypes. The method may be inherited. Method[] getDeclaredMethods( ) –Get all public and nonpublic methods declared in this class, not including those inherited. Method getDeclaredMethod( String name, Class[] argumentTypes) –Get the specified method, public or nonpublic, whose arguments match the types listed in argumentTypes. The inherited methods are not considered.

8 slide 11.8 Advanced Programming 2004, based on LY Stefanus’s Slides Constructor[] getConstructors( ) –Get all public constructors of this class. Constructor getConstructor(Class[] argumentTypes) –Get the public constructor whose arguments match the types listed in argumentTypes. Constructor[] getDeclaredConstructors( ) –Get all public and nonpublic constructors of this class. Constructor getDeclaredConstructor(Class[] argumentTypes) –Get the constructor, public or nonpublic, whose arguments match the types listed in argumentTypes.

9 slide 11.9 Advanced Programming 2004, based on LY Stefanus’s Slides Exercise 1) Write a program which accepts a name of a class and then print the information on –which class (or classes) the given class extends and –which interface (or interfaces) the class implements, hierarchically up to the class Object. (ShowInfoClass.java) 2) Write a program to list all the methods declared in a given class. The name of this class is given as the input to the program. (ListMethods.java)

10 slide 11.10 Advanced Programming 2004, based on LY Stefanus’s Slides Accessing Fields of a Class The class java.lang.reflect.Field represents static variables and instance variables. The class Field has a full set of overloaded accessor methods for all the primitive types (for example, getInt() and setInt(), getBoolean() and setBoolean()) and get() and set() methods for accessing members that are object references. All the data access methods of Field take a reference to the particular object instance that we want to access. Check out an example: (Note that we're accessing the balance field at runtime.)

11 slide 11.11 Advanced Programming 2004, based on LY Stefanus’s Slides AccessField.java import java.lang.reflect.*; public class AccessField { public static void main(String[] arg) { BankAcc ba = new BankAcc(); try { Field balanceField = BankAcc.class.getDeclaredField("balance"); //read the balance field of ba double myBalance = balanceField.getDouble(ba); System.out.println("Initially balance contains " + myBalance); //change it balanceField.setDouble(ba, 600); System.out.println("Now balance contains " + balanceField.getDouble(ba));

12 slide 11.12 Advanced Programming 2004, based on LY Stefanus’s Slides } catch( NoSuchFieldException e1 ) { System.err.println(e1); } catch( IllegalAccessException e2 ) { System.err.println(e2); } class BankAcc { public double balance; //private double balance; }

13 slide 11.13 Advanced Programming 2004, based on LY Stefanus’s Slides Accessing Methods The class java.lang.reflect.Method represents a static or instance method. Subject to the normal security rules, a Method object's invoke() method can be used to call the underlying object's method with specified arguments. This is something like a method pointer in a language such as C++. The first argument to invoke() is the object on which we want to invoke the method. If the method is static, there is no object, so we set the first argument to null. The second argument is an array of objects to be passed as arguments to the method.

14 slide 11.14 Advanced Programming 2004, based on LY Stefanus’s Slides Exercise Write a Java application that takes as command-line arguments the name of a class and the name of a method to invoke. Assume that the method is static and takes one argument. (Invoke.java)

15 slide 11.15 Advanced Programming 2004, based on LY Stefanus’s Slides C:\advprog> java Invoke java.lang.Math sqrt 25.0 Invoked static method: sqrt of class: java.lang.Math with argument: 25.0 Result: 5.0

16 slide 11.16 Advanced Programming 2004, based on LY Stefanus’s Slides Accessing Constructors The java.lang.reflect.Constructor class represents an object constructor that accepts arguments. We can use it, subject to the security rules, to create a new instance of an object. Example:

17 slide 11.17 Advanced Programming 2004, based on LY Stefanus’s Slides import java.lang.reflect.*; import java.util.*; import java.text.*; class AccessConstructor { public static void main( String [] args ) { try { Constructor c = Date.class.getConstructor(new Class[] {Long.TYPE}); Object ob = c.newInstance(new Object[] {new Long(new Date().getTime())} ); DateFormat fmt = DateFormat.getDateInstance(DateFormat.FULL); System.out.println(fmt.format((Date)ob)); } catch ( InstantiationException e ) {//the class is abstract System.err.println(e); } catch ( NoSuchMethodException e2 ) {//that constructor doesn't exist System.err.println(e2); } catch ( IllegalAccessException e3 ) { // we don't have permission to create an instance System.err.println(e3); } catch ( InvocationTargetException e4 ) { // an exception occurred while invoking that constructor System.err.println(e4); }


Download ppt "Slide 11.1 Advanced Programming 2004, based on LY Stefanus’s Slides Reflection Reflection is the ability for a class or object to examine itself. Java."

Similar presentations


Ads by Google