Reflection - PowerPoint PPT Presentation

1 / 20
About This Presentation
Title:

Reflection

Description:

JRE maintains an immutable Class object for each class. ... g.: Class c= java.awt.Button.class ... Class rectangleDefinition=Class.forName('java.awt.Rectangle' ... – PowerPoint PPT presentation

Number of Views:28
Avg rating:3.0/5.0
Slides: 21
Provided by: Jim471
Category:
Tags: java | jre | reflection

less

Transcript and Presenter's Notes

Title: Reflection


1
Reflection
  • Jim Cai

2
Motivation the Class class
  • Why reflection?
  • We need a way to access class information at run
    time
  • Fields, methods, constructors, interfaces..
  • JRE maintains an immutable Class object for each
    class.
  • We say the Class object reflect the class.
  • Not that the Class object can also reflect
    interfaces (with restrictions)

3
Summary
  • Examine classes
  • Getting class name, retrieve Class object.
    Examine methods, fields,
  • Manipulating objects
  • Invoking methods
  • Change fields values

4
Examine classes
5
Retrieving Class object
  • If an instance of the object is available
  • Object.getClass()
  • E.g. Class c myMestery.getClass
  • If an instance of the object is not available
  • If name of the class is unknown until run time
  • Use forName method.
  • E.g. Class cClass.forName (classname)
  • If name of the class is known
  • Append .class to the class name
  • E.g. Class c java.awt.Button.class

6
Getting the class name
  • Every class in the Java programming language has
    a name
  • public class Point int x, y
  • Use getName() method to get the fully qualified
    name of the Class object.

7
What is the output?
  • import java.lang.reflect.
  • import java.awt.
  • class SampleName
  • public static void main(String args)
  • Button b new Button()
  • printName(b)
  • static void printName(Object o)
  • Class c o.getClass()
  • String s c.getName()
  • System.out.println(s)

8
Identify class fields
  • Find out what fields belongs to what class
  • getFields() method returns an array of Field
    objects, each one corresponds to one accessible
    public field
  • Now what if I want information about private (or
    protected) field
  • getDeclaredFields()

9
Example
  • static void printFieldNames(Object o)
  • Class c o.getClass()
  • Field publicFields c.getFields()
  • for (int i 0 i lt publicFields.length i)
  • String fieldName publicFieldsi.getName()
    Class typeClass publicFieldsi.getType()
    String fieldType typeClass.getName()
    System.out.println("Name " fieldName ",
    Type " fieldType)

10
Obtaining methods information
  • Find out what public method belong to a class
  • getMethods() return an array of Method object

11
  • static void showMethods(Object o)
  • Class c o.getClass()
  • Method theMethods c.getMethods()
  • for (int i 0 i lt theMethods.length i)
  • String methodString theMethodsi.getName()
    System.out.println("Name " methodString)
  • String returnString theMethodsi.getReturnTyp
    e().getName() System.out.println(" Return Type
    " returnString)
  • Class parameterTypes theMethodsi.getParame
    terTypes() System.out.print(" Parameter
    Types")
  • for (int k 0 k lt parameterTypes.length k
    )
  • String parameterString parameterTypesk.getNa
    me()
  • System.out.print(" " parameterString)
  • System.out.println()

12
Other class information
  • Discover class modifier
  • Discover class constructor
  • Finding superclass
  • Java API is your friend

13
Manipulating objects
14
Creating objects
  • What? Isnt it trivial?
  • Rectangle r new Rectangle()
  • create an object with the no-argument constructor
  • Class classDefinition Class.forName(className)
  • object classDefinition.newInstance()
  • create an object with a constructor that has
    arguments
  • Create a Class object for the object you want to
    create.
  • Create a constructor object (getConstructor())
  • Create an object by invoking this constructor

15
Example
  • Class rectangleDefinitionClass.forName("java.awt.
    Rectangle")
  • Class intArgsClass new Class int.class,
    int.class
  • Object intArgs new Object height, width
  • intArgsConstructor rectangleDefinition.getConstr
    uctor(intArgsClass)
  • object intArgsConstructor.newInstance(intArgs)

16
Invoking methods
  • Create a Class object that corresponds to the
    object whose method you want to invoke.
  • How? Anyone?
  • Create a Method object by invoking getMethod()
  • Invoke the method by calling invoke()

17
Example
  • //Append one string to another concat()
  • public static String append(String firstWord,
    String secondWord)
  • String result null
  • Class c String.class
  • Class parameterTypes new Class
    String.class
  • Method concatMethod
  • Object arguments new Object secondWord
  • try
  • concatMethod c.getMethod("concat",
    parameterTypes)
  • result (String) concatMethod.invoke(firstWord,
    arguments)
  • catch (NoSuchMethodException e)
  • System.out.println(e)
  • catch (IllegalAccessException e)
  • System.out.println(e)
  • catch (InvocationTargetException e)
  • System.out.println(e)
  • return result

18
Alter field values
  • Create a Class object
  • Create a Field object by using getField()
  • Invoke get() to get the value
  • Invoke set() to set the value
  • Public fields ONLY!

19
Example
  • static void modifyWidth(Rectangle r)
  • Field widthField
  • Class c r.getClass()
  • try
  • widthField c.getField("width")
  • heightFieldc.getField(height)
  • heightValue (Integer) heightField.get(r)
  • widthField.set(r, widthValue)
  • catch (NoSuchFieldException e)
  • System.out.println(e)
  • catch (IllegalAccessException e)
  • System.out.println(e)

20
Key points
  • There is no magic
  • A class is just a data structure
  • A method is just a data structure, too
  • It just happens to contain bytes that look like
    instructions for the interpreter
  • The call stack is another data structure
  • With libraries to give you access to it at
    runtime
  • Many programming tools make use of reflection
  • Junit, your project, debugger etc.
Write a Comment
User Comments (0)
About PowerShow.com