Java Reference
In-Depth Information
But how does our application use it? Once we have the name of the user's class, we need to
create a Class object for that class. This can be done easily using the static method
Class.forName() . Then we can create an instance of it using the Class object's newIn-
stance() method; this calls the class's no-argument constructor. Then we simply cast the
newly constructed object to our Cooklet class, and we can call its methods! It actually takes
longer to describe this code than to look at the code, so let's do that now; see Example 23-7 .
Example 23-7. Cookies.java
public
public class
class Cookies
Cookies {
public
public static
void main ( String [] argv ) {
System . out . println ( "Cookies Application Version 0.0" );
Cooklet cooklet = null
static void
null ;
String cookletClassName = argv [ 0 ];
try
try {
Class < Cooklet > cookletClass =
( Class < Cooklet >) Class . forName ( cookletClassName );
cooklet = cookletClass . newInstance ();
} catch
catch ( Exception e ) {
System . err . println ( "Error " + cookletClassName + e );
}
cooklet . initialize ();
cooklet . work ();
cooklet . terminate ();
}
}
And if we run it?
$ java Cookies DemoCooklet
Cookies Application Version 0.0
I am busy baking cookies.
I am shutting down my ovens now.
$
Of course, this version has rather limited error handling. But you already know how to fix
that. Your ClassLoader can also place classes into a package by constructing a Package ob-
ject; you should do this if loading any medium-sized set of application classes.
Search WWH ::




Custom Search