Reflection - People.cs.uchicago.edu

Download Report

Transcript Reflection - People.cs.uchicago.edu

Reflection
(Reflexion in British English )
Mo Alkhafaji
Reflection
A powerful Java API that allows for dynamic
introspection of classes, interfaces, methods,
and fields. No similar built-in mechanism in
Pascal, C, or C++.
What can you do with Reflection?
It gives you the ability to:
* Discover interfaces, classes, methods and fields.
* Examine and call classes, methods and
constructors.
* Discover types of objects.
* Write very generic code.
The API
* java.lang.Class — This class is used to represent classes.
* java.lang.reflect.Constructor — A special class for
inspecting any of a class's constructor methods.
* java.lang.reflect.Method — This class provides an abstract
means of invoking a Java method from a given class or
object.
The API – Cont.
* java.lang.reflect.Modifier — The Modifier class
is used to determine whether special access
modifiers (such as private, public, or protected)
have been applied to a method or attribute.
* java.lang.reflect.Array — This class is used as
an abstract representation of array objects.
* java.lang.reflect.Field — This class is used to
represent an attribute field.
Practical Examples
* JavaBeans.
* Debuggers.
* Class browsers.
* Introspection.
* Too generic tasks that cannot be grouped into
interfaces or abstract classes.
Practical Examples - Cont.
* A proxy to remote API that can change.
* Changing code without recompiling it!
* Specific requirements.
* Artificial Intelligence (AI) in learning and dynamic
generation of logic.
Disadvantages
*
*
*
*
*
Complex. You cannot use by only looking at the
API.
Error prone.
Slow because classes, methods, and fields
need to be loaded at runtime for introspection.
Security.
It does not update byte code.
Javassist
*
*
*
*
*
Unlike Reflection, Javassist API lets you
manipulate and change byte code generated by
Java compilers.
CtClass, CtMethod, and CtField.
Classes do not have to be loaded into JVM!
You can load using toClass() method in CtClass
to load into JVM.
You can generate new classes and methods
during runtime.
Javassist – Cont.
1. ClassPool pool = ClassPool.getDefault();
2. CtClass pt = pool.get(“mypackage.PNLParser");
3. pt.setSuperclass(pool.get(“ReportParser"));
4. CtMethod m = CtNewMethod.make("public void
printType() { System.out.println(“PNL”); }", pt);
5. pt.addMethod(m);
6. pt.writeFile();