面试题答案
一键面试public class UserConfigFetcher {
private static UserConfig userConfig;
static {
try {
// 模拟fetch调用,实际需要替换为真实的网络请求代码
String apiResponse = "{\"theme\":\"dark\",\"fontSize\":14}";
userConfig = parseUserConfig(apiResponse);
} catch (Exception e) {
userConfig = new UserConfig("light", 16);
}
}
private static UserConfig parseUserConfig(String json) {
// 实际需使用JSON解析库,这里简单模拟
String theme = "light";
int fontSize = 16;
try {
// 解析JSON获取theme和fontSize
int startIndex = json.indexOf("\"theme\":\"") + 8;
int endIndex = json.indexOf("\"", startIndex);
theme = json.substring(startIndex, endIndex);
startIndex = json.indexOf("\"fontSize\":") + 10;
endIndex = json.indexOf(",", startIndex);
if (endIndex == -1) {
endIndex = json.length() - 1;
}
fontSize = Integer.parseInt(json.substring(startIndex, endIndex));
} catch (Exception e) {
// 解析失败使用默认值
}
return new UserConfig(theme, fontSize);
}
public static UserConfig getUserConfig() {
return userConfig;
}
private static class UserConfig {
private String theme;
private int fontSize;
public UserConfig(String theme, int fontSize) {
this.theme = theme;
this.fontSize = fontSize;
}
public String getTheme() {
return theme;
}
public int getFontSize() {
return fontSize;
}
}
}
你可以这样调用:
public class Main {
public static void main(String[] args) {
UserConfigFetcher.UserConfig config = UserConfigFetcher.getUserConfig();
System.out.println("Theme: " + config.getTheme() + ", Font Size: " + config.getFontSize());
}
}
以上代码实现了:
- 在静态块中模拟从API获取用户配置数据,并解析为
UserConfig
对象。 - 处理获取数据时可能出现的错误,若出错则使用默认配置。
- 提供一个静态方法
getUserConfig
供外部获取用户配置数据。
请注意,实际应用中,需将模拟的fetch
调用替换为真实的网络请求,如使用HttpURLConnection
、OkHttp
等库,并使用合适的JSON解析库(如Jackson
、Gson
)来解析JSON数据。