1

I set a JVM option with -Dpath.eai=C:\home\eai. Depending on where I call System.getProperty("path.eai"), I don't have the same result.

Call in a final class attribute's initialization

public static final String DIRECTORY = System.getProperty("path.eai");

private static String printDirectory() {
    System.out.println("My directory is " + DIRECTORY);
}

==> DIRECTORY is null.

Call inside a method

private static final String EAI_PATH_PROPERTY = "path.eai";

public static final String DIRECTORY = getEaiPath();

private static String getEaiPath() {
    String eaiPath = System.getProperty(EAI_PATH_PROPERTY);
    return eaiPath;
}

private static String printDirectory() {
    System.out.println("My directory is " + DIRECTORY);
}

==> DIRECTORY is C:\home\eai

Flyout91
  • 782
  • 10
  • 31

1 Answers1

1

It sounds like this is an order-of-initialization problem. You are probably accessing DIRECTORY from a static block or somewhere where it is trying to access it before it is initialized.

I couldn't reproduce the problem you state, except by initializing something before DIRECTORY is initialized, e.g.

class A {
    public static final String FILE = printDirectory() + "/hello.txt";
    public static final String DIRECTORY = System.getProperty("path.eai");

    private static String printDirectory() {
        System.out.println("My directory is " + DIRECTORY);
        return DIRECTORY;
    }
}

Here, FILE gets initialized before DIRECTORY. At the time FILE is initialized, DIRECTORY is still null.

DodgyCodeException
  • 5,963
  • 3
  • 21
  • 42