The class java.lang.Class
and the reflection package
java.lang.reflect
provide a number of mechanisms
for gathering information from the Java Virtual Machine. Known
collectively as introspection or
reflection, these facilities allow you to load classes on
the fly, to find methods and fields in classes, to generate listings
of them, and to invoke methods on dynamically loaded classes. There
is even a mechanism to let you construct a class from scratch (well,
actually, from an array of bytes) while your program is running. This
is about as close as Java lets you get to the magic, secret internals
of the Java machine.
The JVM Interpreter is a large program, normally written in C and/or C++, that implements the Java Virtual Machine abstraction. You can get the source for Sun’s and other JVMs via the Internet, and could study the JVM for months. Here we concentrate on just a few aspects, and only from the point of view of a programmer using the JVM’s facilities, not how it works internally; that is an implementation detail that varies from one vendor’s JVM to another.
I’ll start with loading an existing class dynamically, move on
to listing the fields and methods of a class and invoking methods,
and end by creating a class on the fly using a
ClassLoader
. One of the more interesting aspects
of Java, and one that accounts for both its flexibility (applets,
servlets) and part of its perceived speed problem, is the notion of
dynamic loading
. For example, even the simplest
“Hello Java” program has to load the class file for your
Hello
class, the class file for its parent
(usually java.lang.Object
), the class for
PrintStream
(since you used
System.out
), the class for
PrintStream
’s parent, and so on. To see this
in action, try something like this:
java -verbose HelloJava | more
To take another example, a browser can download an applet’s bytecode file over the Internet and run it on your desktop. How does it load the class file into the running JVM? We discuss this little bit of Java magic in Section 25.4. The chapter ends with replacement versions of the JDK tools javap and AppletViewer -- the latter doing what a browser does, loading applets at runtime -- and a cross-reference tool that you can use to become a famous Java author by publishing your very own reference to the complete Java API.
3.14.144.216