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 reflexive invocation • Package: java.lang.reflect • class Class, class Method, class Field • Built-In: instanceof 4
Class Object • getClass() 5
Class Class<?> • static forName • getClasses • getConstructor/getConstructors • getField/geFields • getMethod/getMethods • getModifiers • getName • isInstance 6
Class Field • get, getInt, getDouble... • getDeclaringClass • getModifiers • getName • getType • set(obj,value) 7
Example is equivalent to: 8
Class Constructor • getDeclaringClass • getModifiers • getName • getTypeParameters • isVarArgs • newInstance 9
Example is equivalent to: 10
Class Method • getDeclaringClass • getModifiers • getName • getTypeParameters • isVarArgs • invoke(obj,args...) 11
Example is equivalent to: 12
Deeper Example 13
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
Class Proxy • getInvocationHandler • getProxyClass • isProxyClass • newProxyInstance 15
InvocationHandler • invoke 16
Example 17
Performance (1/3) 18
Performances (2/3) for the JIT “T esting direct calls” 19
Performance (3/3) “T esting reflexive calls” 20
Result 10 -2 10 -1 ~ 10 10 2 10 3 Mean time (ns) for regular call: 7 Mean time (ns) for reflexive call: 262 ------- Slowdown factor: 33x 21
Security Issues with Reflection ... 22
So... what about visibility of the method??? • 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!!! 23
Recommend
More recommend