slide 11.1 advanced programming 2004, based on ly stefanus’s slides reflection reflection is the...

17
slide 11. 1 ed 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.

Upload: julian-hutchinson

Post on 17-Dec-2015

213 views

Category:

Documents


1 download

TRANSCRIPT

Page 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

slide 11.1Advanced 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.

Page 2: 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

slide 11.2Advanced 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”

Page 3: 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

slide 11.3Advanced 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.

Page 4: 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

slide 11.4Advanced 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.

Page 5: 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

slide 11.5Advanced 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.

Page 6: 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

slide 11.6Advanced 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)

Page 7: 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

slide 11.7Advanced 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.

Page 8: 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

slide 11.8Advanced 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.

Page 9: 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

slide 11.9Advanced 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)

Page 10: 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

slide 11.10Advanced 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.)

Page 11: 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

slide 11.11Advanced Programming 2004, based on LY Stefanus’s Slides

AccessField.javaimport 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));

Page 12: 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

slide 11.12Advanced 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;

}

Page 13: 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

slide 11.13Advanced 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.

Page 14: 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

slide 11.14Advanced 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)

Page 15: 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

slide 11.15Advanced 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

Page 16: 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

slide 11.16Advanced 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:

Page 17: 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

slide 11.17Advanced 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);

}

}

}