Java Reference
In-Depth Information
this little bit of Java magic in
Loading and Instantiating a Class Dynamically
.
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.
Getting a Class Descriptor
Problem
You want to get a
Class
object from a class name or instance.
Solution
If the type name is known at compile time, you can get the class instance using the compiler
keyword
.class
, which works on any type that is known at compile time, even the eight
primitive types.
Otherwise, if you have an object (an instance of a class), you can call the
java.lang.Object
method
getClass()
, which returns the
Class
object for the object's class (now that was a
mouthful!):
System
.
out
.
println
(
"Trying the ClassName.class keyword:"
);
System
.
out
.
println
(
"Object class: "
+
Object
.
class
);
System
.
out
.
println
(
"String class: "
+
String
.
class
);
System
.
out
.
println
(
"String[] class: "
+
String
[].
class
);
System
.
out
.
println
(
"Calendar class: "
+
Calendar
.
class
);
System
.
out
.
println
(
"Current class: "
+
ClassKeyword
.
class
);
System
.
out
.
println
(
"Class for int: "
+
int
int
.
class
);
System
.
out
.
println
();
System
.
out
.
println
(
"Trying the instance.getClass() method:"
);
System
.
out
.
println
(
"Sir Robin the Brave"
.
getClass
());
System
.
out
.
println
(
Calendar
.
getInstance
().
getClass
());
When we run it, we see: