Java 1.5 Tiger A Developers Notebook [Electronic resources]

David Flanagan, Brett McLaughlin

نسخه متنی -صفحه : 131/ 87
نمايش فراداده

8.5 Shadowing Static Imports

As a final act of complete confusion in your code, you're welcome to shadow your imports, static or otherwise. Shadowing is the process of having a member variable (or field, or method) effectively hide something that is already in the Java namespace through an import.

8.5.1 How do I do that?

Simply declare a member variable named the same as what is imported, and that you want to shadow. Example 8-4 is an example of just that process in action.

Example 8-4. Shadowing an import
package com.oreilly.tiger.ch08;
import static java.lang.System.err;
import static java.lang.System.out;
import java.io.IOException;
import java.io.PrintStream;
public class StaticImporter {
public static void writeError(PrintStream err, String msg)
throws IOException {
// Note that err in the parameter list overshadows the imported err
err.println(msg);
}
public static void main(String[] args) {
if (args.length < 2) {
err.println(
"Incorrect usage: java com.oreilly.tiger.ch08 [arg1] [arg2]");
return;
}
out.println("Good morning, " + args[0]);
out.println("Have a " + args[1] + " day!");
try {
writeError(System.out, "Error occurred.");
} catch (IOException e) {
e.printStackTrace( );
}
}
}

NOTE

Example 8-4 is an updated version of Example 8-1.

Note that a variable named err is defined, local to the writeError( ) method. That variable, in that method, will shadow the err variable imported from java.lang.System. Keep in mind, though, that this adds yet another layer of obfuscation to your code. It's almost always easier to just rename your variable to avoid this type of confusion, and save everyone some headaches:

     public static void writeError(PrintStream errorStream, String msg)
throws IOException {
errorStream.println(msg);
}