How can I set field value before class initialization?

430 views Asked by At

I am reading source code about the java.sql.DriverManager,and found something confusing.Here is the code:

static {
    loadInitialDrivers();
    println("JDBC DriverManager initialized");
}
......
public static void println(String message) {
    synchronized (logSync) {
        if (logWriter != null) {
            logWriter.println(message);

            // automatic flushing is never enabled, so we must do it ourselves
            logWriter.flush();
        }
    }
}

The logWriter have not been set when class initialize,but was called by its static block.So I can't see any log info about this. How can I set field value before class initialization?

2

There are 2 answers

7
Dean Xu On

The only way is to set the logWriter in a Driver implementation.

public class MyDriver implements Driver {

  static {
    // DriverManager will use ServiceLoader to load this class
    DriverManager.setLogWriter(new PrintWriter(System.out));
  }

  ... all methods in Driver
}

Then you will get the log

DriverManager.initialize: jdbc.drivers = null
JDBC DriverManager initialized

EDIT

For @moilejter's question, here give a simple sample of how two classes call each other even they are both not ready.

public class JustTest {
  public static void main(String[] args) throws java.lang.Exception {
    A.i = 2;
  }
}

class A {
  static int i = 1;
  static {
    System.out.println("a block start");
    B.print();
  }

  public static void print() {
    System.out.println("a print: " + B.i);
  }
}

class B {
  static int i = 1;
  static {
    System.out.println("b block start");
    A.print();
  }

  public static void print() {
    System.out.println("b print: " + A.i);
  }
}
1
kira On

You can use this code if u use Console:

DriverManager.setLogWriter(new PrintWriter(System.out));