Datasheet

Generic Methods
In addition to the generic mechanism for classes, generic methods are introduced. The angle brackets for
the parameters appear after all method modifiers but before the return type of the method. Following is
an example of a declaration of a generic method:
static <Elem> void swap(Elem[] a, int i, int j)
{
Elem temp = a[i];
a[i] = a[j];
a[j] = temp;
}
The syntax for the parameters in a generic method is the same as that for generic classes. Type variables can
have bounds just like they do in class declarations. Two methods cannot have the same name and argu-
ment types. If two methods have the same name and argument types, and have the same number of type
variables with the same bounds, then these methods are the same and the compiler will generate an error.
Generics and Exceptions
Type variables are not permitted in catch clauses, but can be used in throws lists of methods. An exam-
ple of using a type variable in the
throws clause follows. The Executor interface is designed to execute
a section of code that may throw an exception specified as a parameter. In this example, the code that
fills in the
execute method might throw an IOException. The specific exception, IOException, is
specified as a parameter when creating a concrete instance of the
Executor interface:
import java.io.*;
interface Executor<E extends Exception> {
void execute() throws E;
}
public class GenericExceptionTest {
public static void main(String args[]) {
try {
Executor<IOException> e =
new Executor<IOException>() {
public void execute() throws IOException
{
// code here that may throw an
// IOException or a subtype of
// IOException
}
};
e.execute();
} catch(IOException ioe) {
System.out.println(“IOException: “ + ioe);
ioe.printStackTrace();
}
}
}
15
Chapter 1: Key Java Language Features and Libraries
05_777106 ch01.qxp 11/28/06 10:43 PM Page 15