20
10/18/08 Matt Swatzell

Reflection In Java

Embed Size (px)

DESCRIPTION

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. - PowerPoint PPT Presentation

Citation preview

Page 1: Reflection In Java

10/18/08 Matt Swatzell

Page 2: 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.

Page 3: Reflection In Java

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

Page 4: Reflection In Java

Code Demo

Code Demo How would you go about doing this?

Page 5: Reflection In Java

The java.lang.Class Class http://java.sun.com/j2se/1.5.0/docs/a

pi/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.

Page 6: Reflection In Java

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”);

Page 7: Reflection In Java

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

Page 8: Reflection In Java

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

Page 9: Reflection In Java

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

Page 10: Reflection In Java

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

Page 11: Reflection In Java

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(int i); toString(int i);

Page 12: Reflection In Java

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);

Page 13: Reflection In Java

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.

Page 14: Reflection In Java

Problems With Reflection

Slow….. Security Problems If not security problems, than

security risks

Page 15: Reflection In Java

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

Page 16: Reflection In Java

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

Page 17: Reflection In Java

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

Page 18: Reflection In Java

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

Page 19: Reflection In Java

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);

}

}

Page 20: Reflection In Java

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.