Re: alias
Christopher Benson-Manica wrote:
NickName <dadada@rock.com> wrote:
I may be jumping guns here. I mean I'm totally new to java and yet, I
feel the need to do something like this for typing much less,
o = System.out.println; // problem, what data type for var of o here?
In other languages, o might be a function pointer, but in Java you're
out of luck. The best you could do, saving yourself a little bit of
typing, would be something like
final PrintStream o = System.out;
o.println( "Hello, world!" );
although it really isn't worth the effort. The alternative, using
reflection to get the println Method from System.out, will save you
neither typing nor brain CPU cycles.
Something similar does sometimes come up where you want to "wrap"
something like System.out.println. For example, you want to log certain
events, but the exact nature of the logging should be irrelevant to
whatever does the logging and should be changeable in a single place.
Then you do this:
public interface Logger {
public void log (String message);
}
//Somewhere else
public class StdoutLogger implements Logger {
public void log (String message) {
System.out.println(message);
}
}
//Somewhere else again
public static void main (String[] args) {
Logger logger = new StdoutLogger();
...
someobject.doSomething(logger, other_args);
...
}
//Somewhere else again
public void doSomething (Logger logger, other_args) {
...
logger.log("Foo");
...
catch (IOException e) {
logger.log("Oops! I/O error");
logger.log(e.toString());
<some sort of recovery>
}
...
}
Later on you might want to use some other Logger. You can make an
AggregatingLogger: (assumes Tiger)
public class AggregatingLogger implements Logger {
private List<Logger> members;
public AggregatingLogger () {
members = new LinkedList<Logger>();
}
public void add (Logger logger) {
members.add(logger);
}
public void log (String message) {
for (Logger logger : members) {
logger.log(message);
}
}
}
Just be careful not to add an aggregating logger to itself, OK? :)