
CMSC 433 – Programming Language
Technologies and Paradigms
Spring 2004
Reflection
April 27, 2004
2
Reflection
• Remember project 1?
–Used reflection to find module class
•http://webserver:port/HelloWorld/Foo
•We’ll cover some basics of reflection
–Highly condensed version of
•Reflection: Java Technology’s Secret Weapon, by
Odendahl (on web page)
3
What is Reflection?
•Makes classes, methods, and fields objects
that can be manipulated at run time
–Can determine fields and methods of class
–Can instantiate class given a String containing
its name
–Can invoke methods given a String with name
–Can create classes an runtime
4
What Reflection Isn’t
•Doesn’t add any power to the language
–Given access to all the source code
•Not the solution to every problem
–Use sparingly, if at all
5
java.lang.Class
•Object of type Class represents a class
–Useful for
•Making instances of a class
•Getting information about fields/methods
–Most uses of reflection start with a Class
• Primitive types also have a Class
–e.g., int.class
6
Getting Some Class
•Use Object method getClass()
–Class c = “hello”.getClass();
•Use class literal
–Class c = String.class;
•Use the class name
–Class c = Class.forName(“java.lang.String”)