THE Java™ Programming Language, Fourth Edition

(Jeff_L) #1
protected final Class<?>defineClass(String name, byte[] data,
int offset, int length)throws ClassFormatError

Returns a Class object for the named class whose binary representation is
held in data. Only the bytes in data from offset to
offset+length-1 are used to define the class. If the bytes in the
subarray do not conform to a valid class file format, a
ClassFormatError is thrown. The defineClass method is
responsible for storing the Class object into the table searched by
findLoadedClass.

An overloaded form of defineClass takes an additional ProtectionDomain argument, while the
above form uses a default protection domain. Protection domains define the security permissions for objects in
that domainagain see "Security" on page 677 for further details. Both forms of defineClass may throw
SecurityException.


Before you can define a class you have to read the bytes for the class, and that is the purpose of
bytesForClass:


protected byte[] bytesForClass(String name)
throws IOException, ClassNotFoundException
{
FileInputStream in = null;
try {
in = streamFor(name + ".class");
int length = in.available(); // get byte count
if (length == 0)
throw new ClassNotFoundException(name);
byte[] buf = new byte[length];
in.read(buf); // read the bytes
return buf;
} finally {
if (in != null)
in.close();
}
}


This method uses streamFor (not shown) to get a FileInputStream to the class's bytecodes, assuming
that the bytecodes are in a file named by the class name with a ".class" appendedstreamFor knows
where to search for the class files to be loaded. We then create a buffer for the bytes, read them all, and return
the buffer.


When the class has been successfully loaded, findClass returns the new Class object returned by
defineClass. There is no way to explicitly unload a class when it is no longer needed. You simply stop
using it, allowing it to be garbage-collected when its ClassLoader is unreachable.


Exercise 16.11: Expand on Game and Player to implement a simple game, such as tic-tac-toe. Score some
Player implementations over several runs each.


16.13.2. Preparing a Class for Use


The class loader assists in only the first stage of making a class available. There are three steps in all:



  1. Loading Getting the bytecodes that implement the class and creating a Class object.

Free download pdf