|
The goal of this section is to show you
some of the advantages of the new APIs introduced with
JDK 1.1. Notably, you'll see the new delegation event
model in action and see how reflection can be used
to get Retrieving a Method object through introspection allows you to call the method without knowing what its exact definition is at the time you write your code. This is what application builder tools, like the BeanBox, must do in order to present users with a list of event handler methods that a given Bean can respond to.
The first several implementations of
The
An action method handles selections from the Choice component:
Not very interesting so far, but the idea is to start simple. This code does have the interesting property of being able to run either as an applet or an application. You can use an HTML file to test these applets, or use the Java interpreter to invoke the program directly:
java ChoiceApplet01
This works because the ChoiceApplet01 has
a main method:
The main method sets up an applet frame an invokes the applet within it. A private appletFrame extends Frame and
provides basic functionality to handle
the destruction of the frame when the
applet is terminiated.
Being able to run the code as a standalone application is just a convenience, but has little to do with the topics at hand: event handling and reflection mechanisms. Introducing Reflection and Method Retrieval With the new Core Reflection API You can use a new construct to get the class for any object in the system: type.getClass().getName() For example, if "s" is a String object, then s.class will return the string "String." With the reflection API, you can get a class from an object, and you can then get lists of instance variables, methods, and ancestors for objects of this class. You can also use the reflection API to test for assignment compatibility. Assignment compatibility answers the question: Can objects of type A be assigned to a variable declared as type B?
Given the string name for a class, you can also invoke a method on
a class. For example given methods declared as
You could invoke either method through a string naming the method:
In the following sections you'll see how to put reflection to good use. Program Source Code A makefile for this lesson which automates source code compilation. You may want to look at the final source file for ChoiceApplet01.java. | |||||||||||
|
| ||||||||||||