Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Read out system environment during startup

What is the best way to read out system environment in an Java application and class visibility function?

I need to e.g. os.name and have designed a class like

private String osName; 

private void readSystemSettings() {
    osName = System.getProperty("os.name");
}

public void printSystemSettings() {
    System.out.println(this.osName);
    ...
}

public SystemEnvironment() {
    readSystemSettings();       
}

public static void main(String[] args) {
    // TODO Auto-generated method stub
}
  1. What are the best practice for getting those information? Call this function always on start-up or only from time to time?

  2. I want to read out those information as soon as the class get instantiated. Therefor the constructor is calling the readSystemSettings() function.

As this is information will always be the same during runtime, I actually need only no stance. Means all variables + functions shall be final. Or am I wrong?

  1. If 2) is correct understanding, how to do?
like image 467
Berton Avatar asked Aug 12 '26 11:08

Berton


1 Answers

You can have a class with all the variables marked as final and then initialize in a static block.

public class SystemProperties{

  public static final String OS_NAME;
  // other properties

  static{
    OS_NAME = System.getProperty("os.name");
    // initialize other properties

  }

}

Else, if you're in a managed environment like Spring or EJB, you can mark SystemProperties as singleton and initialize the variable in a method annotated with @PostContruct.

public class SystemProperties{

  public static String OS_NAME;
  // other properties

  @PostConstruct
  private void init(){
    OS_NAME = System.getProperty("os.name");
    // initialize other properties

  }

}
like image 84
ares Avatar answered Aug 14 '26 23:08

ares



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!