COMP 202: Principles of Object-Oriented Programming II← Dynamic Class Loading →
|Home — Fall 2008|||||Information|||||Resources|||||Exam Resources|||||OwlSpace|||||COMP 201|
In the design of the Temperature Calculator
assignment, we want the program to have the ability to convert between
temperature scales that are not known at compile time. Since you cannot know
the class names of classes not known at compile time, the model cannot simply
create an object of that class by doing
new Celsius() or something
similar that uses the class name directly in the source code.
When the "Add..." button is pressed, the user can enter the
fully qualified class name, i.e. the class name with all the package names
in front of the class (e.g.
java.lang.Object as opposed to just
The starting point of most reflection concerns is a class named Class. In most cases, we will need to import a package named java.lang.reflect to make use of the classes pertaining to reflection.
Class<?> forName(String s).
will return the empty string: ""
Then there is a unique class X that is associated with someClass, and someClass.getConstructors() will return an array of Constructor objects that correspond to all the public constructors for X. Its signature is
T newInstance(Object... args).
Below is a method that makes use of the above class loading capability to
add a new temperature unit to the list of units, after asking the user to enter
the fully qualified class name and storing that name in the
Here is some source code that uses reflection to perform operations on lists.
Copyright © 2008-2010 Mathias Ricken and Stephen Wong