Java Reference
In-Depth Information
which is what the documentation tells us it needs to be, but note that we've
added the word
static
to this declaration.
Static
here means two things:
•You access the variable using the name of the plugin without a plugin
object. In this case,
HelloWorld.logger
will work from anywhere, inside or
outside an object.
•The static variable (
logger
) is common to all
HelloWorld
objects, and lives on,
outside the lifetime of any local variables in any object.
That means that any of the functions within a
HelloWorld
object can come and
go, and their local variables can come and go, but the static variables will
still be there and still remember their values.
Since
logger
is the very first thing we declare inside our plugin, and it's not
inside a function itself, all the functions in our plugin—everything inside this
top pair of
{
and
}
characters—can use it. It's not local to any one function.
That means you can use
logger
anywhere in
HelloWorld.java
:
...
public
void
myFavoriteFunction() {
logger.info(
"Made it this far"
);
}
...
Notice that we don't need any kind of extra declaration; you can just use
logger
anywhere in this plugin that you'd like. That's a very handy technique to trace
what's happening in a plugin: add a
logger
statement and you can print out
the values of variables at that point in the code.
Global variables like these, however, can also be mighty dangerous.
Why are they dangerous? Precisely because
anyone
, anywhere, can change
the value of that variable on you. Maybe you know they did it, but maybe you
don't—even if “they” is “you,” weeks from now. If something goes wrong, you
have to go and examine every single piece of code in the system to try to find
out which piece of code set the variable badly, and why. That's a lot of work
and creates a lot of opportunity to mess things up.
But sometimes you really do need a global variable like that. You may not
want anyone else to change it, but maybe a lot of different pieces of code need
to refer to it. The
logger
is a good example: it's a shared service that all plugins
and the server itself use. We all need access to the logging object, and we
need it in a variable that won't go away. Unlike with a local variable, we want