Reflection Java looking at Java n One of

  • Slides: 23
Download presentation
Reflection

Reflection

Java looking at Java n One of the unusual capabilities of Java is that

Java looking at Java n One of the unusual capabilities of Java is that a program can examine itself n n n You can determine the class of an object You can find out all about a class: its access modifiers, superclass, fields, constructors, and methods You can find out what is in an interface Even if you don’t know the names of things when you write the program, you can: n Create an instance of a class n Get and set instance variables n Invoke a method on an object n Create and manipulate arrays I guess this is called “reflection” because it’s as if a Java program could “look in a mirror” at itself 2

What is reflection for? n n n In “normal” programs you don’t need reflection

What is reflection for? n n n In “normal” programs you don’t need reflection You do need reflection if you are working with programs that process programs Typical examples: n n n A class browser A debugger A GUI builder An IDE, such as Blue. J or Eclipse A program to grade student programs 3

IDEs n Many IDEs are Java programs—what can they do? n n n n

IDEs n Many IDEs are Java programs—what can they do? n n n n Compile a program (easy—just a system call) Load in your program after compilation Find out what classes you have, and what their constructors and methods are Execute your main method Create objects for you even without running your main method Send messages to objects and display the results All these capabilities, except compilation, are done with reflection 4

The Class class n To find out about a class, first get its Class

The Class class n To find out about a class, first get its Class object n n If you have an object obj, you can get its class object with Class c = obj. get. Class(); You can get the class object for the superclass of a Class c with Class sup = c. get. Superclass(); If you know the name of a class (say, Button) at compile time, you can get its class object with Class c = Button. class; If you know the name of a class at run time (in a String variable str), you can get its class object with Class c = Class. for. Name(str); 5

Getting the class name n n n If you have a class object c,

Getting the class name n n n If you have a class object c, you can get the name of the class with c. get. Name() get. Name returns the fully qualified name; that is, Class c = Button. class; String s = c. get. Name(); System. out. println(s); will print java. awt. Button Class and its methods are in java. lang, which is always imported and available 6

Getting all the superclasses n n get. Superclass() returns a Class object (or null

Getting all the superclasses n n get. Superclass() returns a Class object (or null if you call it on Object, which has no superclass) The following code is from the Sun tutorial: static void print. Superclasses(Object o) { Class subclass = o. get. Class(); Class superclass = subclass. get. Superclass(); while (superclass != null) { String class. Name = superclass. get. Name(); System. out. println(class. Name); subclass = superclass; superclass = subclass. get. Superclass(); } } 7

Getting the class modifiers I n n n A Class object has an instance

Getting the class modifiers I n n n A Class object has an instance method get. Modifiers() that returns an int To “decipher” the int result, we need methods of the Modifier class, which is in java. lang. reflect, so: import java. lang. reflect. *; Now we can do things like: if (Modifier. is. Public(m)) { System. out. println("public"); } 8

Getting the class modifiers II n Modifier contains these methods (among others): n n

Getting the class modifiers II n Modifier contains these methods (among others): n n n n public public n static static boolean is. Abstract(int) boolean is. Final(int) boolean is. Interface(int) boolean is. Private(int) boolean is. Protected(int) boolean is. Public(int) String to. String(int) This will return a string such as "public final synchronized strictfp" 9

Getting interfaces n n A class can implement zero or more interfaces get. Interfaces()

Getting interfaces n n A class can implement zero or more interfaces get. Interfaces() returns an array of Class objects n n These are the interfaces implemented by the class More code from Sun: static void print. Interface. Names(Object o) { Class c = o. get. Class(); Class[ ] the. Interfaces = c. get. Interfaces(); for (int i = 0; i < the. Interfaces. length; i++) { String interface. Name = the. Interfaces[i]. get. Name(); System. out. println(interface. Name); } } n Note that zero-length arrays are perfectly legal in Java 10

Examining classes and interfaces n n n The class Class represents both classes and

Examining classes and interfaces n n n The class Class represents both classes and interfaces To determine if a given Class object c is an interface, use c. is. Interface() To find out more about a class object, use: n n n get. Modifiers() get. Fields() // "fields" == "instance variables" get. Constructors() get. Methods() is. Array() 11

Getting Fields n n public Field[] get. Fields() throws Security. Exception n Returns an

Getting Fields n n public Field[] get. Fields() throws Security. Exception n Returns an array of public Fields (variables) n The length of the array may be zero n The fields are not returned in any particular order n Both locally defined and inherited instance variables are returned, but not static variables public Field get. Field(String name) throws No. Such. Field. Exception, Security. Exception n Returns the named public Field n If no immediate field is found, the superclasses and interfaces are searched recursively 12

Using Fields, I n If f is a Field object, then n n f.

Using Fields, I n If f is a Field object, then n n f. get. Name() returns the simple name of the field f. get. Type() returns the type (Class) of the field f. get. Modifiers() returns the Modifiers of the field f. to. String() returns a String containing access modifiers, the type, and the fully qualified field name n n Example: public java. lang. String Person. name f. get. Declaring. Class() returns the Class in which this field is declared 13

Using Fields, II n The values of the fields of an object obj may

Using Fields, II n The values of the fields of an object obj may be accessed with: n n n boolean f. get. Boolean(obj), int f. get. Int(obj), double f. get. Double(obj), etc. , return the value of the field, assuming it is that type or can be widened to that type Object f. get(obj) returns the value of the field, assuming it is an Object void f. set(obj, value), void f. set. Boolean(obj, bool), void f. set. Int(obj, i), void f. get. Double(obj, d), etc. set the value of a field 14

Constructors n If c is a Constructor object, then n n c. get. Name()

Constructors n If c is a Constructor object, then n n c. get. Name() returns the name of the constructor, as a String (this is the same as the name of the class) c. get. Declaring. Class() returns the Class in which this constructor is declared c. get. Modifiers() returns the Modifiers of the constructor c. get. Parameter. Types() returns an array of Class objects, in declaration order c. new. Instance(Object[] initargs) creates and returns a new instance of class c n Arguments that should be primitives are automatically unwrapped as needed 15

Methods n n public Method[] get. Methods() throws Security. Exception n Returns an array

Methods n n public Method[] get. Methods() throws Security. Exception n Returns an array of Method objects n These are the public member methods of the class or interface, including inherited methods n The methods are returned in no particular order public Method get. Method(String name, Class[] parameter. Types) throws No. Such. Method. Exception, Security. Exception 16

Method methods, I n n get. Declaring. Class() n Returns the Class object representing

Method methods, I n n get. Declaring. Class() n Returns the Class object representing the class or interface that declares the method represented by this Method object get. Name() n Returns the name of the method represented by this Method object, as a String get. Modifiers() n Returns the Java language modifiers for the method represented by this Method object, as an integer get. Parameter. Types() n Returns an array of Class objects that represent the formal parameter types, in declaration order, of the method represented by this Method object 17

Method methods, II n n n get. Return. Type() n Returns a Class object

Method methods, II n n n get. Return. Type() n Returns a Class object that represents the formal return type of the method represented by this Method object to. String() n Returns a String describing this Method (typically pretty long) public Object invoke(Object obj, Object[] args) n Invokes the underlying method represented by this Method object, on the specified object with the specified parameters n Individual parameters are automatically unwrapped to match primitive formal parameters 18

Arrays I n To determine whether an object obj is an array, n n

Arrays I n To determine whether an object obj is an array, n n n To find the type of components of the array, n n Get its class c with Class c = obj. get. Class(); Test with c. is. Array() c. get. Component. Type() n Returns null if c is not the class of an array There is an Array class in java. lang. reflect that provides static methods for working with arrays 19

Arrays II n n To create an array, Array. new. Instance(Class component. Type, int

Arrays II n n To create an array, Array. new. Instance(Class component. Type, int size) n This returns, as an Object, the newly created array n n The component. Type may itself be an array n n n You can cast it to the desired type if you like This would create a multiply-dimensioned array The limit on the number of dimensions is usually 255 Array. new. Instance(Class component. Type, int[] size) n This returns, as an Object, the newly created multidimensional array (with size. length dimensions) 20

Arrays III n To get the value of array elements, n n n Array.

Arrays III n To get the value of array elements, n n n Array. get(Object array, int index) returns an Object Array. get. Boolean(Object array, int index) returns a boolean Array. get. Byte(Object array, int index) returns a byte etc. To store values into an array, n n Array. set(Object array, int index, Object value) Array. set. Boolean(Object array, int index, boolean z) Array. set. Byte(Object array, int index, byte b) etc. 21

Concluding comments n Many of these methods throw exceptions that I haven’t described n

Concluding comments n Many of these methods throw exceptions that I haven’t described n n n Reflection isn’t used in “normal” programs, but when you need it, it’s indispensable A related topic is class loaders--the Java that reads in classes as needed n n n For details, see the Java API You can write your own class loaders This is another capability that most languages don’t have I’ve never used reflection for any serious programs, but I think it’s a fascinating capability 22

The End 23

The End 23