在类初始化之前如何设置字段值?

时间:2018-07-26 07:32:04

标签: java class in-class-initialization

我正在阅读有关java.sql.DriverManager的源代码,发现有些混乱。这是代码:

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();
        }
    }
}

在初始化类时尚未设置logWriter,但由其静态块调用了。因此,我看不到任何有关此的日志信息。 如何在类初始化之前设置字段值?

2 个答案:

答案 0 :(得分:0)

唯一的方法是在logWriter实现中设置Driver

public class MyDriver implements Driver {

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

  ... all methods in Driver
}

然后您将获得日志

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

编辑

对于@moilejter的问题,这里给出一个简单的示例,说明两个类即使没有准备好又如何相互调用。

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 :(得分:-1)

如果您使用Console,则可以使用以下代码:

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