1 / 20

Reflection In Java

10/18/08 Matt Swatzell. Reflection In Java. What is Reflection?. Some Definitions…. Reflection is the process by which a program can modify its own behavior. A program that can analyze and modify its own parameters at runtime is considered reflective.

Download Presentation

Reflection In Java

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. 10/18/08 Matt Swatzell Reflection In Java

  2. What is Reflection? • Some Definitions…. • Reflection is the process by which a program can modify its own behavior. • A program that can analyze and modify its own parameters at runtime is considered reflective. • Tools for manipulating code at runtime. • In other words… A way for a program/application to learn about itself, change itself, and perhaps even add to itself.

  3. Some Examples • Reflection is used for many things: • IDE’s / software analysis tools • Debuggers • Server Side Code i.e. ASP.NET • Plug-ins • Frameworks i.e. Java Beans • Imitating function pointers in Java

  4. Code Demo • Code Demo • How would you go about doing this?

  5. The java.lang.Class Class • http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Class.html • JVM always maintains Runtime Type Definition for all objects. • Determines correct methods to call • Class is used for this purpose. • Unique Class object for each type.

  6. java.lang.Class cont. • 3 ways to get the Class class of an object • (any Object).getClass();  For objects that already exist • Scanner scan = new Scanner(System.in); • Class c = scan.getClass(); • (Any type).class  When you only know the type • Works for primitives too • Int.class; • Scanner.class; • Class.forName(“fully qualified path”);  Know the name of class you want • Class c1 = Class.forName(“java.util.Scanner”);

  7. Useful methods in Class • Public string Name(); • returns name of class • Constructor[] getConstructors() • an Array of constructors (more on these later) • Method[] getMethods() • an Array of methods • Field[] getFields() • an Array of fields • Class[] getInterfaces() • an Array of Interfaces • <T> newInstance() • An instance of the class, only works in certain cases

  8. java.lang.reflect.Constructor • Represents a constructor for a class object • Important Methods • Class getDeclaringClass(); • Int getModifiers(); • Why int? • Class[] getParameterTypes(); • Object newInstance(Object[] args); • Creates a new class if parameters are needed

  9. Java.lang.reflect.Method • Represents a method in a class • Useful Methods in Method • Class[] getExceptionTypes(); • Int getModifiers(); • String getName(); • Class[] getParameterTypes(); • Class getReturnType(); • Invoke(Object o, Object[] args); • Exceptions, Exceptions, Exceptions

  10. Java.lang.reflect.Field • Represents a Field within a Class • get(type)(Object obj); • Returns the value of the field in Object obj • set(Type)(Object o) • Sets the value

  11. Two more java.lang.reflector.*’s • Java.lang.reflect.AccessibleObject • Base for Constructor, method, field • Allows you to modify accessibility at runtime. • isAccessible(); • setAccessible(boolean flag); • Breaks with SecurityManagers • java.lang.reflect.Modifier • Takes int and returns facts about modifers on it • isPrivate(inti); • toString(inti);

  12. Can I do it with Arrays? • Java.lang.reflect.Array • get(type)(Object Array, int index); • set(Type)(Object array, int Index, type value); • newInstance(Class type, int length); • New Instance(Class type, int[] dimensions);

  13. Function Pointers (in a way…) • Cannot pass location of method in java • In C/C++ this is possible • Passing functions as parameters • Void doAwesomeness(function awesome); • Reflection provides a handy workaround if you need this functionality • Simply pass method object and call invoke • Before you get too excited… • It not in Java for a reason • Inheritance / Polymorphism usually safer.

  14. Problems With Reflection • Slow….. • Security Problems • If not security problems, than security risks

  15. A brief intro to ClassLoader • Q: So, other than object analyzers, generic toStrings, and function pointers what is Reflection good for? • A: Loading classes dynamincally • Sometimes you will not know all the classes that will be needed. Used by your application • Sometimes the user will want to add their own • Think of VS, Eclipse, some games

  16. ClassLoader cont. • ClassLoader is responsible for loading classes • Every class has reference to ClassLoader the created it. • Only object w/o class loader are generic Objects in arrays. • Primitives have no class loader • The original ClassLoader, (called the bootstrap class loader) has no parent class loader • all others, as objects, do

  17. Boot strap Class Loader • Where does JVM look for classes? • Some are included with application • Custom Defined Ones • Are all of them? • JVM looks in ClassPath for classes, then in program / application • What if you want to look elsewhere? • On your own machine, you could add to ClassPath • Can’t do this on end-user’s

  18. Other Options • Only one really… • Create a new ClassLoader that extends abstract ClassLoader. • Override loadClass • Get location of file • Get byte array of the class data • Call define class and return the result • You now have a class of a type that was unknown until runtime • Problems with inheritance

  19. An example custom Class Loader • Public class customLoader extends ClassLoader { • public class findClass(String name) { • Byte[] b = openFileAndGetByteArray(name); • Return defineClass(name,b,0,b.length); • } • }

  20. Citations • Horstmann , Cay S., and Gary Cornell. Core Java 2 . Volume 1. Santa Clara, CA: Sun Microsystems, 2005. • "The Reflection API." java.sun.com. Sun Microsystems, Web. 19 Nov 2009.

More Related