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
Object
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).
Class.forName("java.lang.String").newInstance()
will return the empty string: ""
Class someClass;
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
Constructor[] getConstructor().
T newInstance(Object... args).
Class<?>[] getParameterTypes().
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 className
string:
Here is some source code that uses reflection to perform operations on lists.
URL: http://www.cs.rice.edu/teaching/202/08-fall/lectures/classLoading/index.shtml
Copyright © 2008-2010 Mathias Ricken and Stephen Wong