Object Oriented Programming in Java Lecture 13 Java

Object Oriented Programming in Java Lecture 13

Java Reflection • Reflection is a feature unique to Java that allows an executing program to examine or “introspect” upon itself, and manipulate properties of the program. • For example, it is possible for a Java class to get the names of its members and display them. • There is no way in C, C++ or other languages to get information about functions defined within a program. • Reflection Classes are found in java. lang. reflect.

An Example import java. lang. reflect. *; public class Get. Methods { public static void main(String[ ] args) { try { Class a = Class. for. Name(args[0]); Method meth[ ] = a. get. Declared. Methods(); for (int i = 0; i < meth. length; i++) System. out. println(meth[ i ]. to. String()); } catch (Throwable exc) { System. err. println(exc); } } } Examples: invoke Get. Methods on java. util. Stack, java. lang. String, and user-defined class Link. Checker. > java Get. Methods java. util. Stack

Using Reflection Classes: 3 Steps 1. Obtain a java. lang. Class object for the class you want to manipulate. For example: Class a = Class. for. Name(“java. lang. String”); gets the class object for String. Class b = int. class; gets class information on types such as int.

Using Reflection Classes: 3 Steps 2. Call a method such as get. Declared. Methods to get a list of methods declared in a class: Class a = Class. for. Name(“java. lang. String”); Method meth[ ] = a. get. Declared. Methods(); 3. Use the reflection API to manipulate this list: Calling to. String() for each element in the meth array displays all methods declared in String.

The Class class • To find out about a class, first get its Class object – 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);

Getting the class name • 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

Getting all the superclasses • 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(); } }

Getting the class modifiers I • 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"); }

Getting the class modifiers II • Modifier contains these methods (among others): – – – – public public 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"

Getting interfaces • A class can implement zero or more interfaces • get. Interfaces() returns an array of Class objects – 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); } } • Note that zero-length arrays are perfectly legal in Java

Examining classes and interfaces • 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: – – – get. Modifiers() get. Fields() // "fields" == "instance variables" get. Constructors() get. Methods() is. Array()
![Getting Fields • public Field[] get. Fields() throws Security. Exception – Returns an array Getting Fields • public Field[] get. Fields() throws Security. Exception – Returns an array](http://slidetodoc.com/presentation_image_h2/058f124fc21aa9935e9357fe085f569c/image-13.jpg)
Getting Fields • public Field[] get. Fields() throws Security. Exception – Returns an array of public Fields (variables) – The length of the array may be zero – The fields are not returned in any particular order – 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 – Returns the named public Field – If no immediate field is found, the superclasses and interfaces are searched recursively

Using Fields, I • If f is a Field object, then – – 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 • Example: public java. lang. String Person. name – f. get. Declaring. Class() returns the Class in which this field is declared

Using Fields, II • The values of the fields of an object obj may be accessed with: – 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

Constructors • If c is a Constructor object, then – 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 • Arguments that should be primitives are automatically unwrapped as needed
![Methods • public Method[] get. Methods() throws Security. Exception – Returns an array of Methods • public Method[] get. Methods() throws Security. Exception – Returns an array of](http://slidetodoc.com/presentation_image_h2/058f124fc21aa9935e9357fe085f569c/image-17.jpg)
Methods • public Method[] get. Methods() throws Security. Exception – Returns an array of Method objects – These are the public member methods of the class or interface, including inherited methods – The methods are returned in no particular order • public Method get. Method(String name, Class[] parameter. Types) throws No. Such. Method. Exception, Security. Exception

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

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

Arrays I • To determine whether an object obj is an array, – Get its class c with Class c = obj. get. Class(); – Test with c. is. Array() • To find the type of components of the array, – c. get. Component. Type() • 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

Arrays II • To create an array, • Array. new. Instance(Class component. Type, int size) – This returns, as an Object, the newly created array • You can cast it to the desired type if you like – The component. Type may itself be an array • 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) – This returns, as an Object, the newly created multidimensional array (with size. length dimensions)

Arrays III • To get the value of array elements, – 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, – – 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.

Applications of Reflection • Parametric Programming • Aspect Oriented Programming • …
- Slides: 23