今天调试以前的同事的程序,竟然发现了一个很隐秘的bug,帖出来大家共享一下,这里还是有关java的类初始化机制的问题。

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class Config {
private static Config instance ;

private InputStream inputStream;
public static Config getInstance(){
if (instance==null) {
try {
instance = new Config();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return instance;
}
private Properties properties;
private Config() throws IOException{
try {
FileInputStream confInput = new FileInputStream(
"config.properties");
Config.getInstance().init(confInput);

} catch (Exception e) {
e.printStackTrace();
System.exit(0);
}
}
public void init(InputStream inputStream) throws IOException{
// System.out.println(inputStream);
this.properties = new Properties();
this.properties.load(inputStream);
}
public String get(String key){
if (this.properties.getProperty(key)==null)
return "";
return this.properties.getProperty(key);
}
}
呵呵,晚上公布答案,答对的并且在上海的请吃一碗桂林米粉

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class Config {
private static Config instance ;
private InputStream inputStream;
public static Config getInstance(){
if (instance==null) {
try {
instance = new Config();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return instance;
}
private Properties properties;
private Config() throws IOException{
try {
FileInputStream confInput = new FileInputStream(
"config.properties");
Config.getInstance().init(confInput);
} catch (Exception e) {
e.printStackTrace();
System.exit(0);
}
}
public void init(InputStream inputStream) throws IOException{
// System.out.println(inputStream);
this.properties = new Properties();
this.properties.load(inputStream);
}
public String get(String key){
if (this.properties.getProperty(key)==null)
return "";
return this.properties.getProperty(key);
}
}呵呵,晚上公布答案,答对的并且在上海的请吃一碗桂林米粉
本文探讨了Java中一个隐秘的bug,该bug涉及类初始化机制。通过一个具体的例子,展示了如何在单例模式下加载配置文件可能出现的问题,并提供了相应的解决思路。


465

被折叠的 条评论
为什么被折叠?



