我在GitHub上面创建了gamma项目,把自己工作(Java游戏服务器编程)中经常用到的代码整理后放了进去。
前一篇文章介绍了如何查找配置表,本篇文章来介绍一下如何把配置表加载到内存。
由于配置表可能在文件里,也可能在数据库里,或者其他地方,所以一个合理的设计可能会是这样:
不过我目前的项目是用JSON文件存放配置表的,所以我只设计了FileConfigLoader和JsonConfigLoader两个类。
public abstract class FileConfigLoader {
public <T extends Config> List<T> load(Class<T> cfgClass, File cfgFile, Charset cs) throws IOException {
return load(cfgClass, new FileInputStream(cfgFile), cs);
}
public <T extends Config> List<T> load(Class<T> cfgClass, InputStream is, Charset cs) throws IOException {
try (Reader reader = new InputStreamReader(is, cs)) {
return load(cfgClass, reader);
}
}
public abstract <T extends Config> List<T> load(Class<T> cfgClass, Reader reader) throws IOException;
}FileConfigLoader是个抽象类,有三个方法,分别从Reader、InputStream和File里读取配置。
public class JsonConfigLoader extends FileConfigLoader {
private static final Gson GSON = new Gson();
private static final Type LIST_TYPE = new TypeToken<ArrayList<JsonObject>>(){}.getType();
private final Gson gson;
public JsonConfigLoader() {
this(GSON);
}
public JsonConfigLoader(Gson gson) {
this.gson = gson;
}
@Override
public <T extends Config> List<T> load(Class<T> cfgClass, Reader reader) {
ArrayList<JsonObject> jsonObjs = gson.fromJson(reader, LIST_TYPE);
ArrayList<T> cfgs = new ArrayList<>(jsonObjs.size());
for (JsonObject jsonObj : jsonObjs) {
cfgs.add(gson.fromJson(jsonObj, cfgClass));
}
return cfgs;
}
}JsonConfigLoader是FileConfigLoader的子类,实现了load(Class, Reader)方法。JsonConfigLoader利用GSON库把JSON格式的数据转换成对象,关于GSON更详细的说明请看这篇文章。原文地址:http://blog.csdn.net/zxhoo/article/details/39697335