MST

星途 面试题库

面试题:JavaScript类中的静态块初始化:异步与依赖管理

创建一个数据获取类,在静态块中通过`fetch`从一个API获取用户配置数据(假设API返回的数据格式为`{theme: 'dark|light', fontSize: number}`)。将获取到的数据作为静态属性保存。同时,静态块中需要处理`fetch`可能出现的错误,并在类外部能够调用一个静态方法获取这个用户配置数据。若获取数据失败,该静态方法应返回一个默认的配置对象`{theme: 'light', fontSize: 16}`。
37.0万 热度难度
编程语言JavaScript

知识考点

AI 面试

面试题答案

一键面试
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());
    }
}

以上代码实现了:

  1. 在静态块中模拟从API获取用户配置数据,并解析为UserConfig对象。
  2. 处理获取数据时可能出现的错误,若出错则使用默认配置。
  3. 提供一个静态方法getUserConfig供外部获取用户配置数据。

请注意,实际应用中,需将模拟的fetch调用替换为真实的网络请求,如使用HttpURLConnectionOkHttp等库,并使用合适的JSON解析库(如JacksonGson)来解析JSON数据。