Re: a question related to "final static" field variable
Mark Space wrote:
www wrote:
I feel it is kind of silly that in order to get to know what the root
directory it is, Worker is forced to have a MyClass in it.
I think I see what you are trying to say. If I understand, you don't
like the fact that there is some dependency that the worker thread knows
about the MyClass class. I think one way to fix this is to use what is
sometimes called a Strategy Pattern or Dependency Injection. Rather
than have Worker know about MyClass, you inject the information into
Worker, thus breaking the dependency.
This sort of approach is certainly something to keep in mind, in case
the situation gets sufficiently complicated to warrant it. I might do it
that way from the start if this were a public interface that cannot be
changed in the future.
However, if the root directory is the only thing that needs this sort of
handling, and the code can be refactored later if it looks like a good
idea, I would give this the KISS treatment.
To do what seems to be the end objective, static access to the args[0]
from the main call:
public class MyClass {
private static String rootDir;
public static String getRootDir() {
// Optionally test for null and throw exception
return rootDir;
}
public static void main(String[] args) {
rootDir = args[0];
}
}
A worker can call MyClass.getRootDir() to get the root directory name.
Short of nasty reflection abuse, a worker cannot modify rootDir.
Patricia