我正在阅读有关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,而是由其静态块调用的。所以我看不到任何关于这个的日志信息。如何在初始化类之前设置字段值?
唯一的方法是在Driver
实现中设置logWriter
。
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);
}
}
如果使用Console
:,则可以使用此代码
DriverManager.setLogWriter(new PrintWriter(System.out));