【问题标题】:How do I get the class type of Object from HashMap<String, Object>?如何从 HashMap<String, Object> 获取 Object 的类类型?
【发布时间】:2022-01-28 13:21:57
【问题描述】:

我有 4 个不同的 Hashmap,它们的值具有不同的类类型。

(Hashmap, Hashmap, Hashmap, Hashmap)

其中每一个在资源文件夹中都有一个相应的目录,其中包含一组 Json 文件。 我想将目录中的所有 Json 文件反序列化为正确的类类型,并将它们存储在作为参数输入的 HashMap 中。

Gson 需要输入我写过#OBJECTCLASS# 的类类型来创建对象。如何从作为方法参数输入的 HashMap 中获取?

//load a hashmap with the objects saved in its resource file
    public static void loadObjsFromDirectory(HashMap<String, Object> map, String directoryPath) {
        File[] files = new File(directoryPath).listFiles();

        //null safety
        if (files == null) {
            System.out.println(filePath + " is empty");
            return;
        }

        Gson gsonDeserializer = new Gson();
        //deserialize each json file and put the created object in its map
        for (File file : files) {
            //make sure the Json file is parsed correctly
            try {
                Object object = gsonDeserializer.fromJson(String.valueOf(file), #OBJECTCLASS#);
                map.put(file.getName(), object);
                System.out.println(file.getName() + " is loaded");
            } catch (JsonParseException e){
                System.out.println(file.getName() + "is incorrectly parsed");
            }
        }
    }

例如

public static void main(String[] args) throws Exception {
    HashMap<String, Class1> map1 = new HashMap<>();
    HashMap<String, Class2> map2 = new HashMap<>();

    Utils.loadObjsFromDirectory(map1, "directoryPath1");
    Utils.loadObjsFromDirectory(map2, "directoryPath2");
}

应该将 directoryPath1 中的所有文件创建为 Class1 对象,并将 directoryPath2 中的所有文件创建为 Class2 对象。

【问题讨论】:

  • 您可以将您的方法更改为 public static void loadObjsFromDirectory(HashMap&lt;String, Object&gt; map, String directoryPath, Class klass) 并以 Utils.loadObjsFromDirectory(map1, "directoryPath1", Class1.class); 或地图值中的任何类的方式调用它

标签: java hashmap gson deserialization


【解决方案1】:

您可以参数化和模仿 Gson 方法并传入 Class 参数:

public static <ExpectedType>void loadObjsFromDirectory(Class<ExpectedType> expectedType, HashMap<String, ExpectedType> map, String directoryPath) {

//later
ExpectedType object = gsonDeserializer.fromJson(String.valueOf(file), expectedType);

ExpectedType 是仅适用于方法声明的类型参数。它不是在代码中任何地方定义的类。

调用代码(main方法)会变成:

public static void main(String[] args) throws Exception {
    HashMap<String, Class1> map1 = new HashMap<>();
    HashMap<String, Class2> map2 = new HashMap<>();

    Utils.loadObjsFromDirectory(Class1.class, map1, "directoryPath1");
    Utils.loadObjsFromDirectory(Class2.class, map2, "directoryPath2");
}

【讨论】:

    猜你喜欢
    • 2014-08-31
    • 2020-01-08
    • 1970-01-01
    • 2013-07-15
    • 1970-01-01
    • 1970-01-01
    • 2014-07-20
    • 2016-03-10
    • 2016-01-17
    相关资源
    最近更新 更多