Java Reflection: Tools for Dynamic Code Manipulation
200 likes | 241 Views
Discover the power of Java reflection, a process that allows programs to modify their own behavior at runtime. Learn how to analyze, modify, and enhance your Java applications using reflection. Explore examples, methods, and best practices.
Java Reflection: Tools for Dynamic Code Manipulation
E N D
Presentation Transcript
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. • 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.
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
Code Demo • Code Demo • How would you go about doing this?
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.
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”);
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
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
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
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
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);
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);
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.
Problems With Reflection • Slow….. • Security Problems • If not security problems, than security risks
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
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
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
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
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); • } • }
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.