1 / 13

Java reflection

Java reflection. 1. Reflection. A system is reflective if it can inspect part of its execution state while it is running. Introspection only reads internal state, without modifying it (also called reification )

newman
Download Presentation

Java reflection

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Java reflection 1

  2. Reflection A system is reflective if it can inspect part of its execution state while it is running. Introspection only reads internal state, without modifying it (also called reification) Reflection enables modifying execution state, and thereby changing system semantics (e.g. Lisp) 2

  3. Meta Object Protocols Reflection applied to Object-Oriented systems The description of how an object system works at a basic level is called a Meta Object Protocol. The ability to change meta-object protocol is a powerful way to modify an object system For example, examine (or change) inheritance hierarchy while running Examine (or change) how inheritance works How method lookup is done in the class hierarchy How methods are called Applications in debugging, customizing, separation of concerns (aspects) Invented in the context of Common Lisp Object System (CLOS). 3

  4. Reflection (Introspection) in Java If permitted by security policy, the Java Reflection API can be used to: Construct new class instances and arrays Access and modify fields (attributes) of objects and classes Invoke methods on objects and classes Access and modify elements of arrays 4

  5. Uses of Reflection Reflection is commonly used by programs which require the ability to examine or modify the runtime behavior of applications running in the Java virtual machine. This is a relatively advanced feature and should be used only by developers who have a strong grasp of the fundamentals of the language. With that caveat in mind, reflection is a powerful technique and can enable applications to perform operations which would otherwise be impossible. • Extensibility Features • An application may make use of external, user-defined classes by creating instances of extensibility objects using their fully-qualified names. • Class Browsers and Visual Development Environments • A class browser needs to be able to enumerate the members of classes. Visual development environments can benefit from making use of type information available in reflection to aid the developer in writing correct code. • Debuggers and Test Tools • Debuggers need to be able to examine private members on classes. Test harnesses can make use of reflection to systematically call a discoverable set APIs defined on a class, to insure a high level of code coverage in a test suite.

  6. Drawbacks of Reflection • Reflection is powerful, but should not be used indiscriminately. If it is possible to perform an operation without using reflection, then it is preferable to avoid using it. The following concerns should be kept in mind when accessing code via reflection. • Performance Overhead • Because reflection involves types that are dynamically resolved, certain Java virtual machine optimizations can not be performed. Consequently, reflective operations have slower performance than their non-reflective counterparts, and should be avoided in sections of code which are called frequently in performance-sensitive applications. • Security Restrictions • Reflection requires a runtime permission which may not be present when running under a security manager. This is in an important consideration for code which has to run in a restricted security context, such as in an Applet. • Exposure of Internals • Since reflection allows code to perform operations that would be illegal in non-reflective code, such as accessing private fields and methods, the use of reflection can result in unexpected side-effects, which may render code dysfunctional and may destroy portability. Reflective code breaks abstractions and therefore may change behavior with upgrades of the platform.

  7. Reflection (Introspection) in Java The Java Reflection API consists of: The class java.lang.Class The interface java.lang.reflect.Member The class java.lang.reflect.Field The class java.lang.reflect.Method The class java.lang.reflect.Constructor The class java.lang.reflect.Array The class java.lang.reflect.Modifier The class java.lang.reflect.InvocationTargetException 7

  8. Reflection Applications (Java) Applications getting run-time information about objects, use: getField[s] getMethod[s] getConstructor[s] Applications getting compile-time information about objects (at the level provided by .class files), use: getDeclaredField[s] getDeclaredMethod[s] getDeclaredConstructor[s] 8

  9. Compile-Time Reflection Applications Macros E.g., verbose methods for debugging Implementing design patterns (e.g., Observer) Aspect-Oriented Programming “Weaving” different aspects into compilable/executable programs e.g., encrypting/decrypting data before remote transmission Syntactic/semantic extensions to the language Adding multiple inheritance Adding mixins 9

  10. Method Dispatching and Multimethods Which method gets dispatched can be decided at compile-time based on declared argument types information (Java), or at run-time with multi-methods (Smalltalk, SALSA). public int m(Object o){ return 1;} public int m(String s){ return 2;} Object o = new Object(); String s = new String(“hi”); Object os = new String(“foo”); m(o); // returns 1 m(s); // returns 2 m(os); // Static dispatch // returns 1; (Java) // Dynamic dispatch // returns 2. (SALSA) What is the difference between compile-time reflection and run-time reflection? Describe the difference between to which method to dispatch in method overloading. 10

  11. Example (1) import java.lang.reflect.*; public class DumpMethods { public static void main(String args[]) { try { Class c = Class.forName(args[0]); Method m[] = c.getDeclaredMethods(); for (int i = 0; i < m.length; i++) System.out.println(m[i].toString()); } catch (Throwable e) { System.err.println(e); } } } 11

  12. Example (2) public class Main { public static void main(String args[]) { try { Class cls = Class.forName("method1"); Method methlist[] = cls.getDeclaredMethods(); for (int i = 0; i < methlist.length; i++) { Method m = methlist[i]; System.out.println("name = " + m.getName()); System.out.println("decl class = " + m.getDeclaringClass()); Class pvec[] = m.getParameterTypes(); for (int j = 0; j < pvec.length; j++) System.out.println("param #" + j + " " + pvec[j]); Class evec[] = m.getExceptionTypes(); for (int j = 0; j < evec.length; j++) System.out.println("exc #" + j + " " + evec[j]); System.out.println("return type = " + m.getReturnType()); System.out.println("-----"); } } catch (Throwable e) { System.err.println(e); } } } import java.lang.reflect.*; public class method1 { private int f1( Object p, int x) throws NullPointerException { if (p == null) throw new NullPointerException(); return x; } } 12

  13. Summary • Reflection methods • Robot class 13

More Related