Reflection in Java Manuel Oriol - May 3rd, 2007 Introductory - - PowerPoint PPT Presentation

reflection in java
SMART_READER_LITE
LIVE PREVIEW

Reflection in Java Manuel Oriol - May 3rd, 2007 Introductory - - PowerPoint PPT Presentation

Reflection in Java Manuel Oriol - May 3rd, 2007 Introductory Example 2 Reflection? Introspection Dynamic reflexive invocations Meta-Classes: classes are instances of a meta-class 3 In Java Limited to introspection and


slide-1
SLIDE 1

Reflection in Java

Manuel Oriol - May 3rd, 2007

slide-2
SLIDE 2

2

Introductory Example

slide-3
SLIDE 3

Reflection?

  • Introspection
  • Dynamic reflexive invocations
  • Meta-Classes: classes are instances of a

meta-class

3

slide-4
SLIDE 4

In Java

  • Limited to introspection and reflexive

invocation

  • Package: java.lang.reflect
  • class Class, class Method, class Field
  • Built-In: instanceof

4

slide-5
SLIDE 5

Class Object

  • getClass()

5

slide-6
SLIDE 6

Class Class<?>

  • static forName
  • getClasses
  • getConstructor/getConstructors
  • getField/geFields
  • getMethod/getMethods
  • getModifiers
  • getName
  • isInstance

6

slide-7
SLIDE 7

Class Field

  • get, getInt, getDouble...
  • getDeclaringClass
  • getModifiers
  • getName
  • getType
  • set(obj,value)

7

slide-8
SLIDE 8

Example

8

is equivalent to:

slide-9
SLIDE 9

Class Constructor

  • getDeclaringClass
  • getModifiers
  • getName
  • getTypeParameters
  • isVarArgs
  • newInstance

9

slide-10
SLIDE 10

Example

10

is equivalent to:

slide-11
SLIDE 11

Class Method

  • getDeclaringClass
  • getModifiers
  • getName
  • getTypeParameters
  • isVarArgs
  • invoke(obj,args...)

11

slide-12
SLIDE 12

Example

12

is equivalent to:

slide-13
SLIDE 13

Deeper Example

13

slide-14
SLIDE 14

Proxy Classes

  • Meant to be used as a simple way to

implement some interfaces.

  • Created at runtime
  • Use a handler to treat requests
  • instanceof is true with a proxy
  • cast is working correctly

14

slide-15
SLIDE 15

Class Proxy

  • getInvocationHandler
  • getProxyClass
  • isProxyClass
  • newProxyInstance

15

slide-16
SLIDE 16

InvocationHandler

  • invoke

16

slide-17
SLIDE 17

Example

17

slide-18
SLIDE 18

Performance (1/3)

18

slide-19
SLIDE 19

Performances (2/3)

19

“T esting direct calls” for the JIT

slide-20
SLIDE 20

Performance (3/3)

20

“T esting reflexive calls”

slide-21
SLIDE 21

Result

Mean time (ns) for regular call: 7 Mean time (ns) for reflexive call: 262

  • Slowdown factor: 33x

21

10-2 10-1 ~ 10 102 103

slide-22
SLIDE 22

Security Issues with Reflection

22

...

slide-23
SLIDE 23

So... what about visibility

  • f the method???

23

  • Short answer: it is respected through the

SecurityException

  • Long answer?

If you define your own SecurityManager and your own ClassLoader then you can do what you want!!!